diff --git a/.ci.yaml b/.ci.yaml index d44bd12b28f..57d08af9844 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -51,7 +51,7 @@ platform_properties: [ {"dependency": "android_sdk", "version": "version:35v1"}, {"dependency": "android_virtual_device", "version": "android_35_google_apis_x64.textpb"}, - {"dependency": "avd_cipd_version", "version": "build_id:8735216702926189361"}, + {"dependency": "avd_cipd_version", "version": "build_id:8733065022087935185"}, {"dependency": "open_jdk", "version": "version:17"} ] os: Ubuntu @@ -68,7 +68,7 @@ platform_properties: [ {"dependency": "android_sdk", "version": "version:35v1"}, {"dependency": "android_virtual_device", "version": "android_34_google_apis_x64.textpb"}, - {"dependency": "avd_cipd_version", "version": "build_id:8735216702926189361"}, + {"dependency": "avd_cipd_version", "version": "build_id:8733065022087935185"}, {"dependency": "open_jdk", "version": "version:17"} ] os: Ubuntu @@ -362,6 +362,7 @@ targets: # are intentionally running it in the devicelab to ensure that it does not # run on a VM in order to avoid noisy results from the benchmark. - name: Linux analyzer_benchmark + bringup: true # Flaky https://github.com/flutter/flutter/issues/158243 recipe: devicelab/devicelab_drone timeout: 60 properties: @@ -391,6 +392,7 @@ targets: - name: Linux packages_autoroller presubmit: false + bringup: true # https://github.com/flutter/flutter/issues/160055 recipe: pub_autoroller/pub_autoroller # This takes a while because we need to fetch network dependencies and run # Gradle for every android app in the repo @@ -411,7 +413,7 @@ targets: - name: Linux_android_emu android views recipe: devicelab/devicelab_drone - bringup: true # https://github.com/flutter/flutter/issues/153445 + bringup: true properties: tags: > ["framework","hostonly","linux"] @@ -505,7 +507,6 @@ targets: ["framework", "hostonly", "shard", "linux"] - name: Linux build_tests_4_5 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -566,6 +567,7 @@ targets: shard: customer_testing tags: > ["framework", "hostonly", "shard", "linux"] + test_timeout_secs: "2700" # Allows 45 minutes (up from 30 default) - name: Linux docs_publish recipe: flutter/docs @@ -635,39 +637,6 @@ targets: - bin/** - .ci.yaml - - name: Linux firebase_abstract_method_smoke_test - presubmit: false - bringup: true # https://github.com/flutter/flutter/issues/147335 - recipe: firebaselab/firebaselab - timeout: 60 - properties: - dependencies: >- - [ - {"dependency": "android_sdk", "version": "version:35v1"}, - {"dependency": "open_jdk", "version": "version:17"} - ] - tags: > - ["firebaselab"] - task_name: abstract_method_smoke_test - physical_devices: >- - [ - "--device", "model=shiba,version=34", - "--device", "model=panther,version=33", - "--device", "model=redfin,version=30" - ] - # TODO(flutter/flutter#123331): This device is flaking. - # "--device", "model=Nexus6P,version=25" - virtual_devices: >- - [ - "--device", "model=Nexus5.gce_x86,version=21", - "--device", "model=Nexus5.gce_x86,version=22", - "--device", "model=Nexus5.gce_x86,version=23", - "--device", "model=Nexus6P,version=25", - "--device", "model=Nexus6P,version=26", - "--device", "model=Nexus6P,version=27", - "--device", "model=NexusLowRes,version=29" - ] - - name: Linux firebase_release_smoke_test recipe: firebaselab/firebaselab bringup: true # https://github.com/flutter/flutter/issues/147335 @@ -1039,6 +1008,10 @@ targets: {"dependency": "chrome_and_driver", "version": "version:125.0.6422.141"}, {"dependency": "open_jdk", "version": "version:17"} ] + # TODO(fujino): delete once propagation from + # https://github.com/flutter/flutter/issues/158521 completes. + drone_dimensions: > + ["os=Linux", "os=Ubuntu-20"] tags: > ["devicelab", "hostonly", "linux"] task_name: plugin_test @@ -1105,6 +1078,24 @@ targets: ["devicelab", "hostonly", "linux"] task_name: linux_desktop_impeller + - name: Linux android_release_builds_exclude_dev_dependencies_test + recipe: devicelab/devicelab_drone + timeout: 60 + properties: + dependencies: >- + [ + {"dependency": "android_sdk", "version": "version:35v1"}, + {"dependency": "chrome_and_driver", "version": "version:125.0.6422.141"}, + {"dependency": "open_jdk", "version": "version:17"} + ] + tags: > + ["devicelab", "hostonly", "linux"] + task_name: android_release_builds_exclude_dev_dependencies_test + runIf: + - dev/** + - bin/** + - .ci.yaml + - name: Linux run_release_test_linux recipe: devicelab/devicelab_drone timeout: 60 @@ -1170,7 +1161,6 @@ targets: - .ci.yaml - name: Linux tool_integration_tests_1_6 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -1197,7 +1187,6 @@ targets: - .ci.yaml - name: Linux tool_integration_tests_2_6 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -1224,7 +1213,6 @@ targets: - .ci.yaml - name: Linux tool_integration_tests_3_6 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -1251,7 +1239,6 @@ targets: - .ci.yaml - name: Linux tool_integration_tests_4_6 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -1278,7 +1265,6 @@ targets: - .ci.yaml - name: Linux tool_integration_tests_5_6 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -1305,7 +1291,6 @@ targets: - .ci.yaml - name: Linux tool_integration_tests_6_6 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -1467,7 +1452,7 @@ targets: - name: Linux_android_emu flutter_driver_android_test recipe: flutter/flutter_drone - bringup: true # https://github.com/flutter/flutter/issues/153445 + bringup: true timeout: 60 properties: shard: flutter_driver_android @@ -1519,23 +1504,6 @@ targets: ["devicelab","hostonly", "linux"] task_name: web_benchmarks_canvaskit - - name: Linux web_benchmarks_html - recipe: devicelab/devicelab_drone - timeout: 60 - properties: - dependencies: >- - [ - {"dependency": "android_sdk", "version": "version:35v1"}, - {"dependency": "chrome_and_driver", "version": "version:125.0.6422.141"} - ] - tags: > - ["devicelab"] - task_name: web_benchmarks_html - runIf: - - dev/** - - bin/** - - .ci.yaml - - name: Linux web_benchmarks_skwasm recipe: devicelab/devicelab_drone presubmit: false @@ -1556,7 +1524,6 @@ targets: - name: Linux web_benchmarks_skwasm_st recipe: devicelab/devicelab_drone - bringup: true presubmit: false timeout: 60 properties: @@ -2236,7 +2203,7 @@ targets: - name: Linux_android_emu android_defines_test recipe: devicelab/devicelab_drone - bringup: true # https://github.com/flutter/flutter/issues/153445 + bringup: true timeout: 60 properties: tags: > @@ -2649,7 +2616,7 @@ targets: - name: Linux_android_emu external_textures_integration_test recipe: devicelab/devicelab_drone - bringup: true # https://github.com/flutter/flutter/issues/153445 + bringup: true timeout: 60 # Functionally the same as "presubmit: false", except that we will run on # presubmit during engine rolls. This test is the *only* automated e2e @@ -3828,6 +3795,7 @@ targets: task_name: complex_layout_macos__start_up - name: Mac_benchmark complex_layout_scroll_perf_macos__timeline_summary + bringup: true # Flaky https://github.com/flutter/flutter/issues/158251 presubmit: false recipe: devicelab/devicelab_drone timeout: 60 @@ -3848,6 +3816,7 @@ targets: shard: customer_testing tags: > ["framework", "hostonly", "shard", "mac"] + test_timeout_secs: "2700" # Allows 45 minutes (up from 30 default) - name: Mac dart_plugin_registry_test recipe: devicelab/devicelab_drone @@ -3918,6 +3887,7 @@ targets: - dev/bots/** - name: Mac_benchmark flutter_view_macos__start_up + bringup: true # Flaky https://github.com/flutter/flutter/issues/159540 presubmit: false recipe: devicelab/devicelab_drone timeout: 60 @@ -4079,6 +4049,7 @@ targets: - .ci.yaml - name: Mac_benchmark hello_world_macos__compile + bringup: true # Flaky https://github.com/flutter/flutter/issues/159542 presubmit: false recipe: devicelab/devicelab_drone timeout: 60 @@ -4873,6 +4844,7 @@ targets: task_name: hello_world_ios__compile - name: Mac_x64 hot_mode_dev_cycle_macos_target__benchmark + bringup: true # Flaky https://github.com/flutter/flutter/issues/158568 recipe: devicelab/devicelab_drone timeout: 60 properties: @@ -5037,6 +5009,7 @@ targets: task_name: macos_chrome_dev_mode - name: Mac_ios microbenchmarks_ios + bringup: true # Flakey https://github.com/flutter/flutter/issues/156457 recipe: devicelab/devicelab_drone presubmit: false timeout: 60 @@ -5405,7 +5378,6 @@ targets: - name: Mac_arm64 mac_desktop_impeller recipe: devicelab/devicelab_drone presubmit: false - bringup: true timeout: 60 properties: dependencies: >- @@ -5417,7 +5389,6 @@ targets: task_name: run_release_test_macos - name: Windows build_tests_1_9 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -5436,7 +5407,6 @@ targets: ["framework", "hostonly", "shard", "windows"] - name: Windows build_tests_2_9 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -5455,7 +5425,6 @@ targets: ["framework", "hostonly", "shard", "windows"] - name: Windows build_tests_3_9 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -5474,7 +5443,6 @@ targets: ["framework", "hostonly", "shard", "windows"] - name: Windows build_tests_4_9 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -5493,7 +5461,6 @@ targets: ["framework", "hostonly", "shard", "windows"] - name: Windows build_tests_5_9 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -5512,7 +5479,6 @@ targets: ["framework", "hostonly", "shard", "windows"] - name: Windows build_tests_6_9 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -5531,7 +5497,6 @@ targets: ["framework", "hostonly", "shard", "windows"] - name: Windows build_tests_7_9 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -5550,7 +5515,6 @@ targets: ["framework", "hostonly", "shard", "windows"] - name: Windows build_tests_8_9 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -5569,7 +5533,6 @@ targets: ["framework", "hostonly", "shard", "windows"] - name: Windows build_tests_9_9 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -5597,6 +5560,7 @@ targets: shard: customer_testing tags: > ["framework", "hostonly", "shard", "windows"] + test_timeout_secs: "2700" # Allows 45 minutes (up from 30 default) - name: Windows framework_tests_libraries recipe: flutter/flutter_drone @@ -6373,7 +6337,6 @@ targets: - name: Windows windows_desktop_impeller recipe: devicelab/devicelab_drone - bringup: true presubmit: false timeout: 60 properties: diff --git a/.github/ISSUE_TEMPLATE/9_first_party_packages.yml b/.github/ISSUE_TEMPLATE/9_first_party_packages.yml index 645d625b116..dc8e3f7c74d 100644 --- a/.github/ISSUE_TEMPLATE/9_first_party_packages.yml +++ b/.github/ISSUE_TEMPLATE/9_first_party_packages.yml @@ -45,6 +45,7 @@ body: - flutter_template_images - go_router - go_router_builder + - google_adsense - google_identity_services_web - google_maps_flutter - google_sign_in diff --git a/.github/dependabot.yml b/.github/dependabot.yml index ee0695bb954..d9e9317d908 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -3,38 +3,16 @@ version: 2 updates: - - package-ecosystem: "bundler" - directory: "/dev/ci/mac" - schedule: - interval: "weekly" - reviewers: - - "christopherfujino" - - "jmagman" - - "keyonghan" - labels: - - "team" - - "team-infra" - - "autosubmit" - - package-ecosystem: "docker" - directory: "/dev/ci/docker_linux" - schedule: - interval: "weekly" - reviewers: - - "christopherfujino" - - "jmagman" - - "keyonghan" - labels: - - "team" - - "team-infra" - - "autosubmit" - package-ecosystem: "github-actions" directory: "/" schedule: - interval: "daily" + interval: "weekly" + groups: + all-github-actions: + patterns: [ "*" ] reviewers: - "christopherfujino" - "jmagman" - - "keyonghan" labels: - "team" - "team-infra" diff --git a/.github/labeler.yml b/.github/labeler.yml index f2aff1e0b61..35c9165ecdb 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -3,6 +3,8 @@ # found in the LICENSE file. # See https://github.com/actions/labeler/blob/main/README.md for docs. +# Use git ls-files '' to see the list of matching files. + 'a: accessibility': - changed-files: - any-glob-to-any-file: @@ -136,6 +138,8 @@ platform-android: - changed-files: - any-glob-to-any-file: - docs/platform/android/**/* + - packages/flutter_tools/*android*' + - packages/flutter_tools/gradle/**/* platform-ios: - changed-files: diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index b69803e49fb..b735596708c 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -19,11 +19,11 @@ jobs: runs-on: ubuntu-latest if: ${{ github.repository == 'flutter/flutter' }} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - name: ./bin/flutter test --coverage run: pushd packages/flutter;../../bin/flutter test --coverage -j 1;popd - name: upload coverage - uses: codecov/codecov-action@b9fd7d16f6d7d1b5d2bec1a2887e65ceed900238 + uses: codecov/codecov-action@7f8b4b4bde536c465e797be725718b88c5d95e0e with: files: packages/flutter/coverage/lcov.info verbose: true diff --git a/.github/workflows/easy-cp.yml b/.github/workflows/easy-cp.yml index c339f115400..98e5e763aa9 100644 --- a/.github/workflows/easy-cp.yml +++ b/.github/workflows/easy-cp.yml @@ -30,7 +30,7 @@ jobs: run: | echo "COMMIT_SHA=$(echo ${{ github.event.pull_request.merge_commit_sha }})" >> $GITHUB_ENV - name: Checkout Flutter Repo - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: repository: flutteractionsbot/flutter path: flutter diff --git a/.github/workflows/minimal.yml b/.github/workflows/minimal.yml index c0eef5141d5..779c1befaba 100644 --- a/.github/workflows/minimal.yml +++ b/.github/workflows/minimal.yml @@ -18,7 +18,7 @@ jobs: pull-requests: write steps: - name: Checkout Flutter Repo - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: repository: flutter/flutter token: ${{ github.token }} diff --git a/AUTHORS b/AUTHORS index 987103964b7..b03820b6a5a 100644 --- a/AUTHORS +++ b/AUTHORS @@ -129,3 +129,4 @@ Flop Dimil Kalathiya Nate Wilson dy0gu +Albert Wolszon diff --git a/CHANGELOG.md b/CHANGELOG.md index f77063c4726..6d5c6adba16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,12 @@ docs/releases/Hotfix-Documentation-Best-Practices.md INTERNAL NOTE --> + +## Flutter 3.27 Changes + +### [3.27.0](https://github.com/flutter/flutter/releases/tag/3.27.0) +Initial stable release. + ## Flutter 3.24 Changes ### [3.24.4](https://github.com/flutter/flutter/releases/tag/3.24.4) - [dart 3.5.4 changelog](https://github.com/dart-lang/sdk/blob/stable/CHANGELOG.md#354---2024-10-17) diff --git a/TESTOWNERS b/TESTOWNERS index 349b34c3b40..77699dcfdb4 100644 --- a/TESTOWNERS +++ b/TESTOWNERS @@ -230,6 +230,7 @@ ## Host only DeviceLab tests /dev/devicelab/bin/tasks/animated_complex_opacity_perf_macos__e2e_summary.dart @cbracken @flutter/desktop +/dev/devicelab/bin/tasks/android_release_builds_exclude_dev_dependencies_test.dart @camsim99 @flutter/android /dev/devicelab/bin/tasks/basic_material_app_macos__compile.dart @cbracken @flutter/desktop /dev/devicelab/bin/tasks/build_aar_module_test.dart @andrewkolos @flutter/tool /dev/devicelab/bin/tasks/build_ios_framework_module_test.dart @jmagman @flutter/tool @@ -290,7 +291,6 @@ /dev/devicelab/bin/tasks/run_release_test_windows.dart @loic-sharma @flutter/tool /dev/devicelab/bin/tasks/technical_debt__cost.dart @Piinks @flutter/framework /dev/devicelab/bin/tasks/web_benchmarks_canvaskit.dart @yjbanov @flutter/web -/dev/devicelab/bin/tasks/web_benchmarks_html.dart @yjbanov @flutter/web /dev/devicelab/bin/tasks/web_benchmarks_skwasm.dart @eyebrowsoffire @flutter/web /dev/devicelab/bin/tasks/web_benchmarks_skwasm_st.dart @eyebrowsoffire @flutter/web /dev/devicelab/bin/tasks/windows_home_scroll_perf__timeline_summary.dart @jonahwilliams @flutter/engine @@ -316,7 +316,6 @@ /dev/integration_tests/deferred_components_test @gmackall @flutter/android ## Firebase tests -/dev/integration_tests/abstract_method_smoke_test @reidbaker @flutter/android /dev/integration_tests/release_smoke_test @reidbaker @flutter/android ## Shards tests diff --git a/analysis_options.yaml b/analysis_options.yaml index e613f771da4..55cb371d591 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -30,6 +30,9 @@ analyzer: # Ignore protoc generated files - "dev/conductor/lib/proto/*" +formatter: + page_width: 100 + linter: rules: # This list is derived from the list of all available lints located at @@ -219,7 +222,7 @@ linter: # - unnecessary_lambdas # has false positives: https://github.com/dart-lang/linter/issues/498 - unnecessary_late - unnecessary_library_directive - # - unnecessary_library_name # blocked on https://github.com/dart-lang/lints/issues/181#issuecomment-2018919034 + # - unnecessary_library_name # blocked on https://github.com/dart-lang/dartdoc/issues/3882 - unnecessary_new - unnecessary_null_aware_assignments - unnecessary_null_aware_operator_on_extension_on_nullable diff --git a/bin/internal/engine.version b/bin/internal/engine.version index b0eeac553b6..576f1990e8a 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -44d788f4651be9addc9cbca34ac2da7fdba80648 +3c263a38f56b74d63c0a8fcc7425f9e499e7d917 diff --git a/bin/internal/flutter_packages.version b/bin/internal/flutter_packages.version index 6347df122d2..2dcfa4f849c 100644 --- a/bin/internal/flutter_packages.version +++ b/bin/internal/flutter_packages.version @@ -1 +1 @@ -bb5a25815cae4125f2a5903a2b376db58cff2e66 +56886ffe11ad677729ffeabcba227c9ad4218635 diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index 187300c87eb..0c0f2c3f534 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -pG2aukmcwvp71aKuS7CLjA4I9qz5FE1c2Spyk7WPYL4C +iWMEbVYaNdH8RJmXZRvPyKsdgjmdNLMZsYIlAJ3xgE0C diff --git a/bin/internal/shared.bat b/bin/internal/shared.bat index 97eee5a9b33..504540b2303 100644 --- a/bin/internal/shared.bat +++ b/bin/internal/shared.bat @@ -52,18 +52,24 @@ GOTO :after_subroutine CALL "%bootstrap_path%" ) - REM Check that git exists and get the revision - SET git_exists=false + REM Check that git exists and get the revision. + WHERE git >NUL 2>&1 + IF "%ERRORLEVEL%" NEQ "0" ( + REM Could not find git. Exit without /B to avoid retrying. + ECHO Error: Unable to find git in your PATH. && EXIT 1 + ) 2>NUL ( - PUSHD "%flutter_root%" - FOR /f %%r IN ('git rev-parse HEAD') DO ( - SET git_exists=true + REM 'FOR /f' spawns a new terminal instance to run the command. If an + REM 'AutoRun' command is defined in the user's registry, that command could + REM change the working directory, and then we wouldn't be in the directory + REM we expect to be in. To prevent this, we need to 'PUSHD %FLUTTER_ROOT%' + REM before getting the git revision. + REM + REM See https://github.com/flutter/flutter/issues/159018 + FOR /f %%r IN ('PUSHD %FLUTTER_ROOT% ^& $git rev-parse HEAD') DO ( SET revision=%%r ) - POPD ) - REM If git didn't execute we don't have git. Exit without /B to avoid retrying. - if %git_exists% == false echo Error: Unable to find git in your PATH. && EXIT 1 SET compilekey="%revision%:%FLUTTER_TOOL_ARGS%" REM Invalidate cache if: diff --git a/dev/a11y_assessments/pubspec.yaml b/dev/a11y_assessments/pubspec.yaml index 0aaecb8f376..fa420cdf2a9 100644 --- a/dev/a11y_assessments/pubspec.yaml +++ b/dev/a11y_assessments/pubspec.yaml @@ -3,7 +3,7 @@ description: A new Flutter project version: 5.0.0+5 environment: - sdk: '>=3.2.0-22.0.dev <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/a11y_assessments/test/expansion_tile_test.dart b/dev/a11y_assessments/test/expansion_tile_test.dart index 98202198cb7..3503680206c 100644 --- a/dev/a11y_assessments/test/expansion_tile_test.dart +++ b/dev/a11y_assessments/test/expansion_tile_test.dart @@ -14,7 +14,7 @@ void main() { expect(find.byType(ExpansionTile), findsExactly(3)); }); - testWidgets('exapansion tile has one h1 tag', (WidgetTester tester) async { + testWidgets('expansion tile has one h1 tag', (WidgetTester tester) async { await pumpsUseCase(tester, ExpansionTileUseCase()); final Finder findHeadingLevelOnes = find.bySemanticsLabel('ExpansionTile Demo'); await tester.pumpAndSettle(); diff --git a/dev/automated_tests/pubspec.yaml b/dev/automated_tests/pubspec.yaml index fc1dd431b1c..bd00d6611b8 100644 --- a/dev/automated_tests/pubspec.yaml +++ b/dev/automated_tests/pubspec.yaml @@ -1,7 +1,7 @@ name: flutter_automated_tests environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/benchmarks/complex_layout/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/dev/benchmarks/complex_layout/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index e67b2808af0..4f746537f28 100644 --- a/dev/benchmarks/complex_layout/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/dev/benchmarks/complex_layout/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -50,6 +50,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/dev/benchmarks/complex_layout/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/dev/benchmarks/complex_layout/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 1b3fe07eaca..ddf44980c7c 100644 --- a/dev/benchmarks/complex_layout/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/dev/benchmarks/complex_layout/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -48,6 +48,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/dev/benchmarks/complex_layout/pubspec.yaml b/dev/benchmarks/complex_layout/pubspec.yaml index 0b4c318c720..1f8e2408acd 100644 --- a/dev/benchmarks/complex_layout/pubspec.yaml +++ b/dev/benchmarks/complex_layout/pubspec.yaml @@ -2,7 +2,7 @@ name: complex_layout description: A benchmark of a relatively complex layout. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/benchmarks/macrobenchmarks/README.md b/dev/benchmarks/macrobenchmarks/README.md index 2f2dce6ce6a..b1c2e92b029 100644 --- a/dev/benchmarks/macrobenchmarks/README.md +++ b/dev/benchmarks/macrobenchmarks/README.md @@ -111,7 +111,7 @@ in `lib/web_benchmarks.dart`. ### How to run a web benchmark Web benchmarks can be run using `flutter run` in debug, profile, and release -modes, using either the HTML or the CanvasKit rendering backend. Note, however, +modes, using either the CanvasKit or the Skwasm rendering backend. Note, however, that running in debug mode will result in worse numbers. Profile mode is useful for profiling in Chrome DevTools because the numbers are close to release mode and the profile contains unobfuscated names. @@ -121,9 +121,6 @@ Example: ```sh cd dev/benchmarks/macrobenchmarks -# Runs in profile mode using the HTML renderer -flutter run --web-renderer=html --profile -d web-server lib/web_benchmarks.dart - # Runs in profile mode using the CanvasKit renderer flutter run --web-renderer=canvaskit --profile -d web-server lib/web_benchmarks.dart ``` @@ -133,9 +130,6 @@ You can also run all benchmarks exactly as the devicelab runs them: ```sh cd dev/devicelab -# Runs using the HTML renderer -../../bin/cache/dart-sdk/bin/dart bin/run.dart -t bin/tasks/web_benchmarks_html.dart - # Runs using the CanvasKit renderer ../../bin/cache/dart-sdk/bin/dart bin/run.dart -t bin/tasks/web_benchmarks_canvaskit.dart ``` diff --git a/dev/benchmarks/macrobenchmarks/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/dev/benchmarks/macrobenchmarks/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 02cf6fadc5c..e587d9b3522 100644 --- a/dev/benchmarks/macrobenchmarks/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/dev/benchmarks/macrobenchmarks/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -48,6 +48,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" enableGPUFrameCaptureMode = "1" allowLocationSimulation = "YES"> false; - static const String canvasBenchmarkName = 'text_canvas_color_grid'; - static const String canvasKitBenchmarkName = 'text_canvas_kit_color_grid'; - - /// Whether to use the new canvas-based text measurement implementation. - final _TestMode _mode; - - num _textLayoutMicros = 0; - - @override - Future setUpAll() async { - super.setUpAll(); - registerEngineBenchmarkValueListener('text_layout', (num value) { - _textLayoutMicros += value; - }); - } - - @override - Future tearDownAll() async { - stopListeningToEngineBenchmarkValues('text_layout'); - } - - @override - void frameWillDraw() { - super.frameWillDraw(); - _textLayoutMicros = 0; - } - - @override - void frameDidDraw() { - // We need to do this before calling [super.frameDidDraw] because the latter - // updates the value of [showWidget] in preparation for the next frame. - // TODO(yjbanov): https://github.com/flutter/flutter/issues/53877 - if (showWidget && _mode != _TestMode.useCanvasKit) { - profile!.addDataPoint( - 'text_layout', - Duration(microseconds: _textLayoutMicros.toInt()), - reported: true, - ); - } - super.frameDidDraw(); - } + static const String benchmarkName = 'text_canvas_kit_color_grid'; @override Widget createWidget() { diff --git a/dev/benchmarks/macrobenchmarks/lib/src/web/recorder.dart b/dev/benchmarks/macrobenchmarks/lib/src/web/recorder.dart index e67fa246688..cecec992012 100644 --- a/dev/benchmarks/macrobenchmarks/lib/src/web/recorder.dart +++ b/dev/benchmarks/macrobenchmarks/lib/src/web/recorder.dart @@ -36,8 +36,8 @@ const int kDefaultTotalSampleCount = _kDefaultWarmUpSampleCount + _kDefaultMeasu /// A benchmark metric that includes frame-related computations prior to /// submitting layer and picture operations to the underlying renderer, such as -/// HTML and CanvasKit. During this phase we compute transforms, clips, and -/// other information needed for rendering. +/// CanvasKit. During this phase we compute transforms, clips, and other +/// information needed for rendering. const String kProfilePrerollFrame = 'preroll_frame'; /// A benchmark metric that includes submitting layer and picture information diff --git a/dev/benchmarks/macrobenchmarks/lib/web_benchmarks.dart b/dev/benchmarks/macrobenchmarks/lib/web_benchmarks.dart index 28ecf098553..1fa13722d4c 100644 --- a/dev/benchmarks/macrobenchmarks/lib/web_benchmarks.dart +++ b/dev/benchmarks/macrobenchmarks/lib/web_benchmarks.dart @@ -36,9 +36,6 @@ import 'src/web/recorder.dart'; typedef RecorderFactory = Recorder Function(); -const bool isCanvasKit = bool.fromEnvironment('FLUTTER_WEB_USE_SKIA'); -const bool isSkwasm = bool.fromEnvironment('FLUTTER_WEB_USE_SKWASM'); - /// List of all benchmarks that run in the devicelab. /// /// When adding a new benchmark, add it to this map. Make sure that the name @@ -70,34 +67,17 @@ final Map benchmarks = { BenchMouseRegionGridHover.benchmarkName: () => BenchMouseRegionGridHover(), BenchMouseRegionMixedGridHover.benchmarkName: () => BenchMouseRegionMixedGridHover(), BenchWrapBoxScroll.benchmarkName: () => BenchWrapBoxScroll(), - if (!isSkwasm) ...{ - // Platform views are not yet supported with Skwasm. - // https://github.com/flutter/flutter/issues/126346 - BenchPlatformViewInfiniteScroll.benchmarkName: () => BenchPlatformViewInfiniteScroll.forward(), - BenchPlatformViewInfiniteScroll.benchmarkNameBackward: () => BenchPlatformViewInfiniteScroll.backward(), - }, + BenchPlatformViewInfiniteScroll.benchmarkName: () => BenchPlatformViewInfiniteScroll.forward(), + BenchPlatformViewInfiniteScroll.benchmarkNameBackward: () => BenchPlatformViewInfiniteScroll.backward(), BenchMaterial3Components.benchmarkName: () => BenchMaterial3Components(), BenchMaterial3Semantics.benchmarkName: () => BenchMaterial3Semantics(), BenchMaterial3ScrollSemantics.benchmarkName: () => BenchMaterial3ScrollSemantics(), - // Skia-only benchmarks - if (isCanvasKit || isSkwasm) ...{ - BenchTextLayout.canvasKitBenchmarkName: () => BenchTextLayout.canvasKit(), - BenchBuildColorsGrid.canvasKitBenchmarkName: () => BenchBuildColorsGrid.canvasKit(), - BenchTextCachedLayout.canvasKitBenchmarkName: () => BenchTextCachedLayout.canvasKit(), + BenchTextLayout.benchmarkName: () => BenchTextLayout(), + BenchBuildColorsGrid.benchmarkName: () => BenchBuildColorsGrid(), + BenchTextCachedLayout.benchmarkName: () => BenchTextCachedLayout(), - // The HTML renderer does not decode frame-by-frame. It just drops an - // element and lets it animate automatically with no feedback to the - // framework. So this benchmark only makes sense in CanvasKit. - BenchImageDecoding.benchmarkName: () => BenchImageDecoding(), - }, - - // HTML-only benchmarks - if (!isCanvasKit && !isSkwasm) ...{ - BenchTextLayout.canvasBenchmarkName: () => BenchTextLayout.canvas(), - BenchTextCachedLayout.canvasBenchmarkName: () => BenchTextCachedLayout.canvas(), - BenchBuildColorsGrid.canvasBenchmarkName: () => BenchBuildColorsGrid.canvas(), - }, + BenchImageDecoding.benchmarkName: () => BenchImageDecoding(), }; final LocalBenchmarkServerClient _client = LocalBenchmarkServerClient(); diff --git a/dev/benchmarks/macrobenchmarks/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/dev/benchmarks/macrobenchmarks/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 1104e1c1d05..de3bf5aab57 100644 --- a/dev/benchmarks/macrobenchmarks/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/dev/benchmarks/macrobenchmarks/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -48,6 +48,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/dev/benchmarks/macrobenchmarks/pubspec.yaml b/dev/benchmarks/macrobenchmarks/pubspec.yaml index b73432cf337..b465637478e 100644 --- a/dev/benchmarks/macrobenchmarks/pubspec.yaml +++ b/dev/benchmarks/macrobenchmarks/pubspec.yaml @@ -2,7 +2,7 @@ name: macrobenchmarks description: Performance benchmarks using flutter drive. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/benchmarks/microbenchmarks/lib/benchmark_collection.dart b/dev/benchmarks/microbenchmarks/lib/benchmark_collection.dart index 02efa6c2b2e..b109e4a4f59 100644 --- a/dev/benchmarks/microbenchmarks/lib/benchmark_collection.dart +++ b/dev/benchmarks/microbenchmarks/lib/benchmark_collection.dart @@ -16,6 +16,7 @@ import 'foundation/change_notifier_bench.dart' as change_notifier_bench; import 'foundation/clamp.dart' as clamp; import 'foundation/decode_and_parse_asset_manifest.dart' as decode_and_parse_asset_manifest; +import 'foundation/observer_list_bench.dart' as observer_list_bench; import 'foundation/platform_asset_bundle.dart' as platform_asset_bundle; import 'foundation/standard_message_codec_bench.dart' as standard_message_codec_bench; @@ -64,6 +65,7 @@ Future main() async { 'foundation/decode_and_parse_asset_manifest.dart', decode_and_parse_asset_manifest.execute ), + ('foundation/observer_list_bench.dart', observer_list_bench.execute), ( 'geometry/matrix_utils_transform_bench.dart', matrix_utils_transform_bench.execute @@ -125,8 +127,8 @@ Future main() async { final ArgResults results = parser.parse(mainArgs); final List selectedTests = results.multiOption('tests'); - // Shuffle the tests becauase we don't want order dependent tests. - // It is the responsibily of the infra to tell us what the seed value is, + // Shuffle the tests because we don't want order dependent tests. + // It is the responsibility of the infra to tell us what the seed value is, // in case we want to have the seed stable for some time period. final List tests = benchmarks.where((Benchmark e) => selectedTests.contains(e.$1)).toList(); tests.shuffle(Random(int.parse(results.option('seed')!))); diff --git a/dev/benchmarks/microbenchmarks/lib/foundation/observer_list_bench.dart b/dev/benchmarks/microbenchmarks/lib/foundation/observer_list_bench.dart new file mode 100644 index 00000000000..82501225921 --- /dev/null +++ b/dev/benchmarks/microbenchmarks/lib/foundation/observer_list_bench.dart @@ -0,0 +1,172 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/animation.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../common.dart'; + +const int _kNumIterationsList = 2 << 10; +const int _kNumIterationsHashed = 2 << 15; +const List callbackCounts = [1, 10, 100, 500]; + +class TestAnimationController extends AnimationController { + TestAnimationController() : super(vsync: const TestVSync()); + + @override + void notifyListeners() => super.notifyListeners(); +} + +Future execute() async { + assert(false, + "Don't run benchmarks in debug mode! Use 'flutter run --release'."); + + final BenchmarkResultPrinter printer = BenchmarkResultPrinter(); + + void runNotifyListenersLoopWithObserverList( + int totalIterations, { + bool failRemoval = false, + bool addResult = true, + }) { + final String suffix = failRemoval ? 'removalFail' : 'removalSuccess'; + final String name = 'notifyListeners:ObserverList:$suffix'; + + void miss() {} + + for (final int callbackCount in callbackCounts) { + final int iterations = totalIterations ~/ callbackCount; + + final ObserverList observerList = + ObserverList(); + for (int i = 0; i < callbackCount; ++i) { + observerList.add( + switch (failRemoval) { + false => () { + final VoidCallback first = + (observerList.iterator..moveNext()).current; + + observerList.remove(first); + observerList.add(first); + }, + true => () => observerList.remove(miss), + }, + ); + } + + final Stopwatch watch = Stopwatch()..start(); + + for (int i = 0; i < iterations; ++i) { + final List list = observerList.toList(growable: false); + for (final VoidCallback cb in list) { + if (observerList.contains(cb)) { + cb(); + } + } + } + + watch.stop(); + + if (addResult) { + printer.addResult( + description: '$name ($callbackCount callbacks)', + value: watch.elapsedMicroseconds / iterations, + unit: 'µs per iteration', + name: '$name$callbackCount', + ); + } + } + } + + void runNotifyListenersLoopWithHashedObserverList( + int totalIterations, { + bool addResult = true, + }) { + const String name = 'notifyListeners:HashedObserverList'; + + for (final int callbackCount in callbackCounts) { + final int iterations = totalIterations ~/ callbackCount; + + final HashedObserverList observerList = + HashedObserverList(); + for (int i = 0; i < callbackCount; ++i) { + observerList.add(() { + final VoidCallback first = + (observerList.iterator..moveNext()).current; + + observerList.remove(first); + observerList.add(first); + }); + } + + final Stopwatch watch = Stopwatch()..start(); + + for (int i = 0; i < iterations; ++i) { + final List list = observerList.toList(growable: false); + for (final VoidCallback cb in list) { + if (observerList.contains(cb)) { + cb(); + } + } + } + + watch.stop(); + + if (addResult) { + printer.addResult( + description: '$name ($callbackCount callbacks)', + value: watch.elapsedMicroseconds / iterations, + unit: 'µs per iteration', + name: '$name$callbackCount', + ); + } + } + } + + void runNotifyListenersLoopWithAnimationController( + int totalIterations, { + bool addResult = true, + }) { + const String name = 'notifyListeners:AnimationController'; + + for (final int callbackCount in callbackCounts) { + final int iterations = totalIterations ~/ callbackCount; + + final TestAnimationController controller = TestAnimationController(); + for (int i = 0; i < callbackCount; ++i) { + late final VoidCallback cb; + cb = () { + controller.removeListener(cb); + controller.addListener(cb); + }; + controller.addListener(cb); + } + + final Stopwatch watch = Stopwatch()..start(); + + for (int i = 0; i < iterations; ++i) { + controller.notifyListeners(); + } + + watch.stop(); + + if (addResult) { + printer.addResult( + description: '$name ($callbackCount callbacks)', + value: watch.elapsedMicroseconds / iterations, + unit: 'µs per iteration', + name: '$name$callbackCount', + ); + } + } + } + + runNotifyListenersLoopWithObserverList(_kNumIterationsList); + runNotifyListenersLoopWithObserverList(_kNumIterationsList, + failRemoval: true); + runNotifyListenersLoopWithHashedObserverList(_kNumIterationsHashed); + runNotifyListenersLoopWithAnimationController(_kNumIterationsHashed); + + printer.printToStdout(); +} diff --git a/dev/benchmarks/microbenchmarks/pubspec.yaml b/dev/benchmarks/microbenchmarks/pubspec.yaml index 63562f4d8dc..86dc74ee800 100644 --- a/dev/benchmarks/microbenchmarks/pubspec.yaml +++ b/dev/benchmarks/microbenchmarks/pubspec.yaml @@ -2,7 +2,7 @@ name: microbenchmarks description: Small benchmarks for very specific parts of the Flutter framework. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: meta: 1.15.0 diff --git a/dev/benchmarks/multiple_flutters/module/pubspec.yaml b/dev/benchmarks/multiple_flutters/module/pubspec.yaml index 149b17e7ddf..123d0ef29cf 100644 --- a/dev/benchmarks/multiple_flutters/module/pubspec.yaml +++ b/dev/benchmarks/multiple_flutters/module/pubspec.yaml @@ -4,7 +4,7 @@ description: A module that is embedded in the multiple_flutters benchmark test. version: 1.0.0+1 environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/benchmarks/platform_channels_benchmarks/pubspec.yaml b/dev/benchmarks/platform_channels_benchmarks/pubspec.yaml index c15f9bb594c..ba652da09c0 100644 --- a/dev/benchmarks/platform_channels_benchmarks/pubspec.yaml +++ b/dev/benchmarks/platform_channels_benchmarks/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/benchmarks/platform_views_layout/pubspec.yaml b/dev/benchmarks/platform_views_layout/pubspec.yaml index 0b7c4e93823..3f481699527 100644 --- a/dev/benchmarks/platform_views_layout/pubspec.yaml +++ b/dev/benchmarks/platform_views_layout/pubspec.yaml @@ -2,7 +2,7 @@ name: platform_views_layout description: A benchmark for platform views. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/benchmarks/platform_views_layout_hybrid_composition/pubspec.yaml b/dev/benchmarks/platform_views_layout_hybrid_composition/pubspec.yaml index 4aa0d35fd2b..0abdb42ff12 100644 --- a/dev/benchmarks/platform_views_layout_hybrid_composition/pubspec.yaml +++ b/dev/benchmarks/platform_views_layout_hybrid_composition/pubspec.yaml @@ -2,7 +2,7 @@ name: platform_views_layout_hybrid_composition description: A benchmark for platform views, using hybrid composition on android. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/benchmarks/test_apps/stocks/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/dev/benchmarks/test_apps/stocks/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index e67b2808af0..4f746537f28 100644 --- a/dev/benchmarks/test_apps/stocks/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/dev/benchmarks/test_apps/stocks/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -50,6 +50,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/dev/benchmarks/test_apps/stocks/lib/i18n/stock_strings_en.dart b/dev/benchmarks/test_apps/stocks/lib/i18n/stock_strings_en.dart index 7865abd9a29..094331da2ea 100644 --- a/dev/benchmarks/test_apps/stocks/lib/i18n/stock_strings_en.dart +++ b/dev/benchmarks/test_apps/stocks/lib/i18n/stock_strings_en.dart @@ -5,6 +5,8 @@ // THE FOLLOWING FILES WERE GENERATED BY `flutter gen-l10n`. +// ignore: unused_import +import 'package:intl/intl.dart' as intl; import 'stock_strings.dart'; // ignore_for_file: type=lint diff --git a/dev/benchmarks/test_apps/stocks/lib/i18n/stock_strings_es.dart b/dev/benchmarks/test_apps/stocks/lib/i18n/stock_strings_es.dart index c49643aca0c..4b2754145f4 100644 --- a/dev/benchmarks/test_apps/stocks/lib/i18n/stock_strings_es.dart +++ b/dev/benchmarks/test_apps/stocks/lib/i18n/stock_strings_es.dart @@ -5,6 +5,8 @@ // THE FOLLOWING FILES WERE GENERATED BY `flutter gen-l10n`. +// ignore: unused_import +import 'package:intl/intl.dart' as intl; import 'stock_strings.dart'; // ignore_for_file: type=lint diff --git a/dev/benchmarks/test_apps/stocks/pubspec.yaml b/dev/benchmarks/test_apps/stocks/pubspec.yaml index 242c5af83ae..a6116281201 100644 --- a/dev/benchmarks/test_apps/stocks/pubspec.yaml +++ b/dev/benchmarks/test_apps/stocks/pubspec.yaml @@ -1,7 +1,7 @@ name: stocks environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/bots/analyze.dart b/dev/bots/analyze.dart index 49a4e1f0fa1..c0bfff7184c 100644 --- a/dev/bots/analyze.dart +++ b/dev/bots/analyze.dart @@ -22,6 +22,7 @@ import 'custom_rules/analyze.dart'; import 'custom_rules/avoid_future_catcherror.dart'; import 'custom_rules/no_double_clamp.dart'; import 'custom_rules/no_stop_watches.dart'; +import 'custom_rules/protect_public_state_subtypes.dart'; import 'custom_rules/render_box_intrinsics.dart'; import 'run_command.dart'; import 'utils.dart'; @@ -180,7 +181,12 @@ Future run(List arguments) async { // Only run the private lints when the code is free of type errors. The // lints are easier to write when they can assume, for example, there is no // inheritance cycles. - final List rules = [noDoubleClamp, noStopwatches, renderBoxIntrinsicCalculation]; + final List rules = [ + noDoubleClamp, + noStopwatches, + renderBoxIntrinsicCalculation, + protectPublicStateSubtypes, + ]; final String ruleNames = rules.map((AnalyzeRule rule) => '\n * $rule').join(); printProgress('Analyzing code in the framework with the following rules:$ruleNames'); await analyzeWithRules(flutterRoot, rules, @@ -2120,7 +2126,8 @@ Future lintKotlinFiles(String workingDirectory) async { 'To reproduce this lint locally:\n' '1. Identify the CIPD version tag used to resolve this particular version of ktlint (check the dependencies section of this shard in the ci.yaml). \n' '2. Download that version from https://chrome-infra-packages.appspot.com/p/flutter/ktlint/linux-amd64/+/\n' - '3. From the repository root, run `/ktlint --editorconfig=$editorConfigRelativePath --baseline=$baselineRelativePath`'; + '3. From the repository root, run `/ktlint --editorconfig=$editorConfigRelativePath --baseline=$baselineRelativePath`\n' + 'Alternatively, if you use Android Studio, follow the docs at docs/platforms/android/Kotlin-android-studio-formatting.md to enable auto formatting.'; foundError([errorMessage]); } } @@ -2239,6 +2246,7 @@ const Set kExecutableAllowlist = { 'dev/tools/gen_keycodes/bin/gen_keycodes', 'dev/tools/repackage_gradle_wrapper.sh', 'dev/tools/bin/engine_hash.sh', + 'dev/tools/format.sh', 'packages/flutter_tools/bin/macos_assemble.sh', 'packages/flutter_tools/bin/tool_backend.sh', diff --git a/dev/bots/check_code_samples.dart b/dev/bots/check_code_samples.dart index f365dc22ba2..ae2cbe91740 100644 --- a/dev/bots/check_code_samples.dart +++ b/dev/bots/check_code_samples.dart @@ -142,29 +142,18 @@ class SampleChecker { // Get a list of the filenames that were not found in the source files. final List missingFilenames = checkForMissingLinks(exampleFilenames, exampleLinks); - // Get a list of any tests that are missing, as well as any that used to be - // missing, but have been implemented. - final (List missingTests, List noLongerMissing) = checkForMissingTests(exampleFilenames); + // Get a list of any tests that are missing. + final List missingTests = checkForMissingTests(exampleFilenames); // Remove any that we know are exceptions (examples that aren't expected to be // linked into any source files). These are typically template files used to // generate new examples. missingFilenames.removeWhere((String file) => _knownUnlinkedExamples.contains(file)); - if (missingFilenames.isEmpty && missingTests.isEmpty && noLongerMissing.isEmpty && malformedLinks.isEmpty) { + if (missingFilenames.isEmpty && missingTests.isEmpty && malformedLinks.isEmpty) { return true; } - if (noLongerMissing.isNotEmpty) { - final StringBuffer buffer = StringBuffer('The following tests have been implemented! Huzzah!:\n'); - for (final File name in noLongerMissing) { - buffer.writeln(' ${getRelativePath(name)}'); - } - buffer.writeln('However, they now need to be removed from the _knownMissingTests'); - buffer.write('list in the script $_scriptLocation.'); - foundError(buffer.toString().split('\n')); - } - if (missingTests.isNotEmpty) { final StringBuffer buffer = StringBuffer('The following example test files are missing:\n'); for (final File name in missingTests) { @@ -279,35 +268,14 @@ class SampleChecker { return '${path.join(testPath, path.basenameWithoutExtension(example.path))}_test.dart'; } - (List, List) checkForMissingTests(List exampleFilenames) { + List checkForMissingTests(List exampleFilenames) { final List missingTests = []; - final List noLongerMissingTests = []; for (final File example in exampleFilenames) { final File testFile = filesystem.file(getTestNameForExample(example, examples)); - final String name = path.relative(testFile.absolute.path, from: flutterRoot.absolute.path); if (!testFile.existsSync()) { missingTests.add(testFile); - } else if (_knownMissingTests.contains(name.replaceAll(r'\', '/'))) { - noLongerMissingTests.add(testFile); } } - // Skip any that we know are missing. - missingTests.removeWhere( - (File test) { - final String name = path.relative(test.absolute.path, from: flutterRoot.absolute.path).replaceAll(r'\', '/'); - return _knownMissingTests.contains(name); - }, - ); - return (missingTests, noLongerMissingTests); + return missingTests; } } - -// These tests are known to be missing. They should all eventually be -// implemented, but until they are we allow them, so that we can catch any new -// examples that are added without tests. -// -// TODO(gspencergoog): implement the missing tests. -// See https://github.com/flutter/flutter/issues/130459 -final Set _knownMissingTests = { - 'examples/api/test/material/color_scheme/dynamic_content_color.0_test.dart', -}; diff --git a/dev/bots/custom_rules/protect_public_state_subtypes.dart b/dev/bots/custom_rules/protect_public_state_subtypes.dart new file mode 100644 index 00000000000..b43891b02ac --- /dev/null +++ b/dev/bots/custom_rules/protect_public_state_subtypes.dart @@ -0,0 +1,101 @@ +// Copyright 2014 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. + +// TODO(nate-thegrate): remove this file if @protected changes, or add a test if it doesn't. +// https://github.com/dart-lang/sdk/issues/57094 + +import 'package:analyzer/dart/analysis/results.dart'; +import 'package:analyzer/dart/ast/ast.dart'; +import 'package:analyzer/dart/ast/visitor.dart'; +import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/type.dart'; + +import '../utils.dart'; +import 'analyze.dart'; + +final AnalyzeRule protectPublicStateSubtypes = _ProtectPublicStateSubtypes(); + +class _ProtectPublicStateSubtypes implements AnalyzeRule { + final Map> _errors = >{}; + + @override + void applyTo(ResolvedUnitResult unit) { + final _StateSubclassVisitor visitor = _StateSubclassVisitor(); + unit.unit.visitChildren(visitor); + final List unprotected = visitor.unprotectedMethods; + if (unprotected.isNotEmpty) { + _errors.putIfAbsent(unit, () => []).addAll(unprotected); + } + } + + @override + void reportViolations(String workingDirectory) { + if (_errors.isEmpty) { + return; + } + + foundError( + [ + for (final MapEntry> entry in _errors.entries) + for (final MethodDeclaration method in entry.value) + '${locationInFile(entry.key, method, workingDirectory)}: $method - missing "@protected" annotation.', + '\nPublic State subtypes should add @protected when overriding methods,', + 'to avoid exposing internal logic to developers.', + ], + ); + } + + @override + String toString() => 'Add "@protected" to public State subtypes'; +} + +class _StateSubclassVisitor extends SimpleAstVisitor { + final List unprotectedMethods = []; + + /// Holds the `State` class [DartType]. + static DartType? stateType; + + static bool isPublicStateSubtype(InterfaceElement element) { + if (!element.isPublic) { + return false; + } + if (stateType != null) { + return element.allSupertypes.contains(stateType); + } + for (final InterfaceType superType in element.allSupertypes) { + if (superType.element.name == 'State') { + stateType = superType; + return true; + } + } + return false; + } + + @override + void visitClassDeclaration(ClassDeclaration node) { + if (isPublicStateSubtype(node.declaredElement!)) { + node.visitChildren(this); + } + } + + /// Checks whether overridden `State` methods have the `@protected` annotation, + /// and adds the declaration to [unprotectedMethods] if not. + @override + void visitMethodDeclaration(MethodDeclaration node) { + switch (node.name.lexeme) { + case 'initState': + case 'didUpdateWidget': + case 'didChangeDependencies': + case 'reassemble': + case 'deactivate': + case 'activate': + case 'dispose': + case 'build': + case 'debugFillProperties': + if (!node.declaredElement!.hasProtected) { + unprotectedMethods.add(node); + } + } + } +} diff --git a/dev/bots/docs.sh b/dev/bots/docs.sh index da0c0f69658..9a9dae07b7a 100755 --- a/dev/bots/docs.sh +++ b/dev/bots/docs.sh @@ -121,7 +121,7 @@ function generate_docs() { # Install and activate dartdoc. # When updating to a new dartdoc version, please also update # `dartdoc_options.yaml` to include newly introduced error and warning types. - "$DART" pub global activate dartdoc 8.2.0 + "$DART" pub global activate dartdoc 8.3.0 # Build and install the snippets tool, which resides in # the dev/docs/snippets directory. diff --git a/dev/bots/pubspec.yaml b/dev/bots/pubspec.yaml index c3dfa2f128a..89358df2ea6 100644 --- a/dev/bots/pubspec.yaml +++ b/dev/bots/pubspec.yaml @@ -2,7 +2,7 @@ name: tests_on_bots description: Scripts which run on bots. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: analyzer: 6.11.0 diff --git a/dev/bots/run_command.dart b/dev/bots/run_command.dart index f39d89650b0..7372f60b193 100644 --- a/dev/bots/run_command.dart +++ b/dev/bots/run_command.dart @@ -162,6 +162,15 @@ Future runCommand(String executable, List arguments, { }) async { final String commandDescription = '${path.relative(executable, from: workingDirectory)} ${arguments.join(' ')}'; final String relativeWorkingDir = workingDirectory ?? path.relative(io.Directory.current.path); + if (dryRun) { + printProgress(_prettyPrintRunCommand(executable, arguments, workingDirectory)); + return CommandResult._( + 0, + Duration.zero, + '$executable ${arguments.join(' ')}', + 'Simulated execution due to --dry-run', + ); + } final Command command = await startCommand(executable, arguments, workingDirectory: workingDirectory, @@ -205,6 +214,23 @@ Future runCommand(String executable, List arguments, { return result; } +final String _flutterRoot = path.dirname(path.dirname(path.dirname(path.fromUri(io.Platform.script)))); + +String _prettyPrintRunCommand(String executable, List arguments, String? workingDirectory) { + final StringBuffer output = StringBuffer(); + + // Print CWD relative to the root. + output.write('|> '); + output.write(path.relative(executable, from: _flutterRoot)); + if (workingDirectory != null) { + output.write(' (${path.relative(workingDirectory, from: _flutterRoot)})'); + } + output.writeln(': '); + output.writeAll(arguments.map((String a) => ' $a'), '\n'); + + return output.toString(); +} + /// Specifies what to do with the command output from [runCommand] and [startCommand]. enum OutputMode { /// Forwards standard output and standard error streams to the test process' diff --git a/dev/bots/suite_runners/run_android_java11_integration_tool_tests.dart b/dev/bots/suite_runners/run_android_java11_integration_tool_tests.dart index 3ad18cad69f..99e1a5b042d 100644 --- a/dev/bots/suite_runners/run_android_java11_integration_tool_tests.dart +++ b/dev/bots/suite_runners/run_android_java11_integration_tool_tests.dart @@ -8,6 +8,20 @@ import 'package:path/path.dart' as path; import '../utils.dart'; +/// To run this test locally: +/// +/// 1. Connect an Android device or emulator. +/// 2. Run `dart pub get` in dev/bots +/// 3. Set flutter to use Java 11 +/// flutter config --jdk-dir= +/// On a Mac you can run `/usr/libexec/java_home -V1 to find the installed +/// versions of java. Remember to clear this value after testing. +/// `flutter config --jdk-dir=` +/// 4. Run the following command from the root of the Flutter repository: +/// +/// ```sh +/// SHARD=android_java11_tool_integration_tests bin/cache/dart-sdk/bin/dart dev/bots/test.dart +/// ``` Future androidJava11IntegrationToolTestsRunner() async { final String toolsPath = path.join(flutterRoot, 'packages', 'flutter_tools'); diff --git a/dev/bots/suite_runners/run_flutter_driver_android_tests.dart b/dev/bots/suite_runners/run_flutter_driver_android_tests.dart index 52fe47ef96e..a4aa5d7c77d 100644 --- a/dev/bots/suite_runners/run_flutter_driver_android_tests.dart +++ b/dev/bots/suite_runners/run_flutter_driver_android_tests.dart @@ -9,14 +9,16 @@ import '../utils.dart'; /// To run this test locally: /// /// 1. Connect an Android device or emulator. -/// 2. Run the following command from the root of the Flutter repository: +/// 2. Run `dart pub get` in dev/bots +/// 3. Run the following command from the root of the Flutter repository: /// /// ```sh /// SHARD=flutter_driver_android bin/cache/dart-sdk/bin/dart dev/bots/test.dart /// ``` /// -/// For debugging, it is recommended to instead just run and launch these tests +/// For debugging, you need to instead run and launch these tests /// individually _in_ the `dev/integration_tests/native_driver_test` directory. +/// Comparisons against goldens cant happen locally. Future runFlutterDriverAndroidTests() async { print('Running Flutter Driver Android tests...'); diff --git a/dev/bots/suite_runners/run_web_tests.dart b/dev/bots/suite_runners/run_web_tests.dart index 4064c8c27a8..5bbbc597c35 100644 --- a/dev/bots/suite_runners/run_web_tests.dart +++ b/dev/bots/suite_runners/run_web_tests.dart @@ -105,7 +105,7 @@ class WebTestsSuite { testAppDirectory: path.join('packages', 'integration_test', 'example'), target: path.join('test_driver', 'failure.dart'), buildMode: buildMode, - renderer: 'canvaskit', + webRenderer: 'canvaskit', // This test intentionally fails and prints stack traces in the browser // logs. To avoid confusion, silence browser output. silenceBrowserOutput: true, @@ -115,7 +115,7 @@ class WebTestsSuite { target: path.join('integration_test', 'example_test.dart'), driver: path.join('test_driver', 'integration_test.dart'), buildMode: buildMode, - renderer: 'canvaskit', + webRenderer: 'canvaskit', expectWriteResponseFile: true, expectResponseFileContent: 'null', ), @@ -124,7 +124,7 @@ class WebTestsSuite { target: path.join('integration_test', 'extended_test.dart'), driver: path.join('test_driver', 'extended_integration_test.dart'), buildMode: buildMode, - renderer: 'canvaskit', + webRenderer: 'canvaskit', expectWriteResponseFile: true, expectResponseFileContent: ''' { @@ -177,7 +177,7 @@ class WebTestsSuite { testAppDirectory: path.join(flutterRoot, 'examples', 'hello_world'), target: 'test_driver/smoke_web_engine.dart', buildMode: 'profile', - renderer: 'auto', + webRenderer: 'auto', ), () => _runGalleryE2eWebTest('debug'), () => _runGalleryE2eWebTest('debug', canvasKit: true), @@ -278,7 +278,7 @@ class WebTestsSuite { await _runFlutterDriverWebTest( target: path.join('test_driver', '$name.dart'), buildMode: buildMode, - renderer: renderer, + webRenderer: renderer, testAppDirectory: path.join(flutterRoot, 'dev', 'integration_tests', 'web_e2e_tests'), ); } @@ -286,7 +286,7 @@ class WebTestsSuite { Future _runFlutterDriverWebTest({ required String target, required String buildMode, - required String renderer, + required String webRenderer, required String testAppDirectory, String? driver, bool expectFailure = false, @@ -318,7 +318,24 @@ class WebTestsSuite { '-d', 'web-server', '--$buildMode', - '--web-renderer=$renderer', + // '--web-renderer=$webRenderer', + '--dart-define=FLUTTER_WEB_AUTO_DETECT=false', + if (webRenderer == 'skwasm') ...[ + // See: WebRendererMode.dartDefines[skwasm] + '--dart-define=FLUTTER_WEB_USE_SKIA=false', + '--dart-define=FLUTTER_WEB_USE_SKWASM=true', + ], + if (webRenderer == 'canvaskit') ...[ + // See: WebRendererMode.dartDefines[canvaskit] + '--dart-define=FLUTTER_WEB_USE_SKIA=true', + '--dart-define=FLUTTER_WEB_USE_SKWASM=false', + ], + if (webRenderer == 'html') ...[ + // See: WebRendererMode.dartDefines[html] + '--dart-define=FLUTTER_WEB_USE_SKIA=false', + '--dart-define=FLUTTER_WEB_USE_SKWASM=false', + ], + ], expectNonZeroExit: expectFailure, workingDirectory: testAppDirectory, @@ -695,7 +712,23 @@ class WebTestsSuite { '-v', '--platform=chrome', if (useWasm) '--wasm', - '--web-renderer=$webRenderer', + '--dart-define=FLUTTER_WEB_AUTO_DETECT=false', + // '--web-renderer=$webRenderer', + if (webRenderer == 'skwasm') ...[ + // See: WebRendererMode.dartDefines[skwasm] + '--dart-define=FLUTTER_WEB_USE_SKIA=false', + '--dart-define=FLUTTER_WEB_USE_SKWASM=true', + ], + if (webRenderer == 'canvaskit') ...[ + // See: WebRendererMode.dartDefines[canvaskit] + '--dart-define=FLUTTER_WEB_USE_SKIA=true', + '--dart-define=FLUTTER_WEB_USE_SKWASM=false', + ], + if (webRenderer == 'html') ...[ + // See: WebRendererMode.dartDefines[html] + '--dart-define=FLUTTER_WEB_USE_SKIA=false', + '--dart-define=FLUTTER_WEB_USE_SKWASM=false', + ], '--dart-define=DART_HHH_BOT=$runningInDartHHHBot', ...flutterTestArgs, ...tests, @@ -708,7 +741,9 @@ class WebTestsSuite { // metriciFile is a transitional file that needs to be deleted once it is parsed. // TODO(godofredoc): Ensure metricFile is parsed and aggregated before deleting. // https://github.com/flutter/flutter/issues/146003 - metricFile.deleteSync(); + if (!dryRun) { + metricFile.deleteSync(); + } } // The `chromedriver` process created by this test. diff --git a/dev/bots/test.dart b/dev/bots/test.dart index 3b8a17c0a78..f88ce8ca896 100644 --- a/dev/bots/test.dart +++ b/dev/bots/test.dart @@ -4,14 +4,12 @@ // Runs the tests for the flutter/flutter repository. // -// // By default, test output is filtered and only errors are shown. (If a // particular test takes longer than _quietTimeout in utils.dart, the output is // shown then also, in case something has hung.) // // --verbose stops the output cleanup and just outputs everything verbatim. // -// // By default, errors are non-fatal; all tests are executed and the output // ends with a summary of the errors that were detected. // @@ -19,10 +17,10 @@ // // --abort-on-error causes the script to exit immediately when hitting an error. // -// // By default, all tests are run. However, the tests support being split by -// shard and subshard. (Inspect the code to see what shards and subshards are -// supported.) +// shard and subshard. Inspect the code to see what shards and subshards are +// supported, or run with `--dry-run` to get a list of tests that _would_ have +// been executed. // // If the CIRRUS_TASK_NAME environment variable exists, it is used to determine // the shard and sub-shard, by parsing it in the form shard-subshard-platform, @@ -43,7 +41,6 @@ // // --test-randomize-ordering-seed= sets the shuffle seed for reproducing runs. // -// // All other arguments are treated as arguments to pass to the flutter tool when // running tests. @@ -96,6 +93,7 @@ const String CIRRUS_TASK_NAME = 'CIRRUS_TASK_NAME'; Future main(List args) async { try { printProgress('STARTING ANALYSIS'); + bool dryRunArgSet = false; for (final String arg in args) { if (arg.startsWith('--local-engine=')) { localEngineEnv['FLUTTER_LOCAL_ENGINE'] = arg.substring('--local-engine='.length); @@ -116,10 +114,16 @@ Future main(List args) async { onError = () { system.exit(1); }; + } else if (arg == '--dry-run') { + dryRunArgSet = true; + printProgress('--dry-run enabled. Tests will not actually be executed.'); } else { flutterTestArgs.add(arg); } } + if (dryRunArgSet) { + enableDryRun(); + } if (Platform.environment.containsKey(CIRRUS_TASK_NAME)) { printProgress('Running task: ${Platform.environment[CIRRUS_TASK_NAME]}'); } @@ -527,6 +531,9 @@ Future _flutterBuild( } bool _allTargetsCached(File performanceFile) { + if (dryRun) { + return true; + } final Map data = json.decode(performanceFile.readAsStringSync()) as Map; final List> targets = (data['targets']! as List) diff --git a/dev/bots/test/test_test.dart b/dev/bots/test/test_test.dart index 2350e9bba48..49372b3f074 100644 --- a/dev/bots/test/test_test.dart +++ b/dev/bots/test/test_test.dart @@ -154,6 +154,15 @@ void main() { expectExitCode(result, 255); expect(result.stdout, contains('Invalid subshard name')); }); + + test('--dry-run prints every test that would run', () async { + final ProcessResult result = await runScript( + {}, + ['--dry-run'], + ); + expectExitCode(result, 0); + expect(result.stdout, contains('|> bin/flutter')); + }, testOn: 'posix'); }); test('selectTestsForSubShard distributes tests amongst subshards correctly', () async { diff --git a/dev/bots/utils.dart b/dev/bots/utils.dart index be8ab9b028d..ae78a021e7c 100644 --- a/dev/bots/utils.dart +++ b/dev/bots/utils.dart @@ -68,9 +68,27 @@ const String CIRRUS_TASK_NAME = 'CIRRUS_TASK_NAME'; final Map localEngineEnv = {}; /// The arguments to pass to `flutter test` (typically the local engine -/// configuration) -- prefilled with the arguments passed to test.dart. +/// configuration) -- prefilled with the arguments passed to test.dart. final List flutterTestArgs = []; +/// Whether execution should be simulated for debugging purposes. +/// +/// When `true`, calls to [runCommand] print to [io.stdout] instead of running +/// the process. This is useful for determining what an invocation of `test.dart` +/// _might_ due if not invoked with `--dry-run`, or otherwise determine what the +/// different test shards and sub-shards are configured as. +bool get dryRun => _dryRun ?? false; + +/// Switches [dryRun] to `true`. +/// +/// Expected to be called at most once during execution of a process. +void enableDryRun() { + if (_dryRun != null) { + throw StateError('Should only be called at most once'); + } + _dryRun = true; +} +bool? _dryRun; const int kESC = 0x1B; const int kOpenSquareBracket = 0x5B; @@ -135,6 +153,10 @@ final List _pendingLogs = []; Timer? _hideTimer; // When this is null, the output is verbose. void foundError(List messages) { + if (dryRun) { + printProgress(messages.join('\n')); + return; + } assert(messages.isNotEmpty); // Make the error message easy to notice in the logs by // wrapping it in a red box. @@ -342,6 +364,8 @@ Future runDartTest(String workingDirectory, { bool ensurePrecompiledTool = true, bool shuffleTests = true, bool collectMetrics = false, + List? tags, + bool runSkipped = false, }) async { int? cpus; final String? cpuVariable = Platform.environment['CPU']; // CPU is set in cirrus.yml @@ -379,6 +403,10 @@ Future runDartTest(String workingDirectory, { '--coverage=$coverage', if (perTestTimeout != null) '--timeout=${perTestTimeout.inMilliseconds}ms', + if (runSkipped) + '--run-skipped', + if (tags != null) + ...tags.map((String t) => '--tags=$t'), if (testPaths != null) for (final String testPath in testPaths) testPath, @@ -407,6 +435,10 @@ Future runDartTest(String workingDirectory, { removeLine: useBuildRunner ? (String line) => line.startsWith('[INFO]') : null, ); + if (dryRun) { + return; + } + final TestFileReporterResults test = TestFileReporterResults.fromFile(metricFile); // --file-reporter name final File info = fileSystem.file(path.join(flutterRoot, 'error.log')); info.writeAsStringSync(json.encode(test.errors)); @@ -502,7 +534,9 @@ Future runFlutterTest(String workingDirectory, { // metriciFile is a transitional file that needs to be deleted once it is parsed. // TODO(godofredoc): Ensure metricFile is parsed and aggregated before deleting. // https://github.com/flutter/flutter/issues/146003 - metricFile.deleteSync(); + if (!dryRun) { + metricFile.deleteSync(); + } if (outputChecker != null) { final String? message = outputChecker(result); @@ -587,7 +621,7 @@ List selectIndexOfTotalSubshard(List tests, {String subshardKey = kSubs required int subShardCount, }) { // While there exists a closed formula figuring out the range of tests the - // subshard is resposible for, modeling this as a simulation of distributing + // subshard is responsible for, modeling this as a simulation of distributing // items equally into buckets is more intuitive. // // A bucket represents how many tests a subshard should be allocated. @@ -613,27 +647,33 @@ List selectIndexOfTotalSubshard(List tests, {String subshardKey = kSubs } Future _runFromList(Map items, String key, String name, int positionInTaskName) async { - String? item = Platform.environment[key]; - if (item == null && Platform.environment.containsKey(CIRRUS_TASK_NAME)) { - final List parts = Platform.environment[CIRRUS_TASK_NAME]!.split('-'); - assert(positionInTaskName < parts.length); - item = parts[positionInTaskName]; - } - if (item == null) { - for (final String currentItem in items.keys) { - printProgress('$bold$key=$currentItem$reset'); - await items[currentItem]!(); + try { + String? item = Platform.environment[key]; + if (item == null && Platform.environment.containsKey(CIRRUS_TASK_NAME)) { + final List parts = Platform.environment[CIRRUS_TASK_NAME]!.split('-'); + assert(positionInTaskName < parts.length); + item = parts[positionInTaskName]; } - } else { - printProgress('$bold$key=$item$reset'); - if (!items.containsKey(item)) { - foundError([ - '${red}Invalid $name: $item$reset', - 'The available ${name}s are: ${items.keys.join(", ")}', - ]); - return; + if (item == null) { + for (final String currentItem in items.keys) { + printProgress('$bold$key=$currentItem$reset'); + await items[currentItem]!(); + } + } else { + printProgress('$bold$key=$item$reset'); + if (!items.containsKey(item)) { + foundError([ + '${red}Invalid $name: $item$reset', + 'The available ${name}s are: ${items.keys.join(", ")}', + ]); + return; + } + await items[item]!(); + } + } catch (_) { + if (!dryRun) { + rethrow; } - await items[item]!(); } } diff --git a/dev/conductor/bin/conductor b/dev/conductor/bin/conductor index 3a5735a53e8..3cf839a40ef 100755 --- a/dev/conductor/bin/conductor +++ b/dev/conductor/bin/conductor @@ -38,6 +38,6 @@ REPO_DIR="$BIN_DIR/../../.." DART_BIN="$REPO_DIR/bin/dart" # Ensure pub get has been run in the repo before running the conductor -(cd "$REPO_DIR/dev/conductor/core"; "$DART_BIN" pub get 1>&2) +(cd "$REPO_DIR/dev/conductor/core"; "$DART_BIN" pub get >/dev/null) exec "$DART_BIN" --enable-asserts "$REPO_DIR/dev/conductor/core/bin/cli.dart" "$@" diff --git a/dev/conductor/core/lib/src/next.dart b/dev/conductor/core/lib/src/next.dart index 5ab02f00820..394ffc983d9 100644 --- a/dev/conductor/core/lib/src/next.dart +++ b/dev/conductor/core/lib/src/next.dart @@ -141,7 +141,7 @@ class NextContext extends Context { if (!autoAccept) { final bool response = await prompt( 'Has CI passed for the engine PR?\n\n' - '${state_import.luciConsoleLink(state.releaseChannel, 'engine')}' + '${state_import.luciConsoleLink(state.engine.candidateBranch, 'engine')}' ); if (!response) { stdio.printError('Aborting command.'); diff --git a/dev/conductor/core/lib/src/state.dart b/dev/conductor/core/lib/src/state.dart index fa0fc303a82..08e04fbdca4 100644 --- a/dev/conductor/core/lib/src/state.dart +++ b/dev/conductor/core/lib/src/state.dart @@ -47,21 +47,19 @@ const String stablePostReleaseMsg = """ // * `String presentState(pb.ConductorState state)` - pretty print the state file. // This is a little easier to read than the raw JSON. -String luciConsoleLink(String channel, String groupName) { +String luciConsoleLink(String candidateBranch, String repoName) { assert( - globals.kReleaseChannels.contains(channel), - 'channel "$channel" not recognized', + globals.releaseCandidateBranchRegex.hasMatch(candidateBranch), + 'Malformed candidateBranch argument passed: "$candidateBranch"', ); assert( - ['flutter', 'engine', 'packaging'].contains(groupName), - 'group named $groupName not recognized', + ['flutter', 'engine', 'packaging'].contains(repoName), + 'group named $repoName not recognized', ); - final String consoleName = - channel == 'master' ? groupName : '${channel}_$groupName'; - if (groupName == 'packaging') { + if (repoName == 'packaging') { return 'https://luci-milo.appspot.com/p/dart-internal/g/flutter_packaging/console'; } - return 'https://ci.chromium.org/p/flutter/g/$consoleName/console'; + return 'https://flutter-dashboard.appspot.com/#/build?repo=$repoName&branch=$candidateBranch'; } String defaultStateFilePath(Platform platform) { @@ -93,7 +91,7 @@ String presentState(pb.ConductorState state) { buffer.writeln('\tCurrent git HEAD: ${state.engine.currentGitHead}'); buffer.writeln('\tPath to checkout: ${state.engine.checkoutPath}'); buffer.writeln( - '\tPost-submit LUCI dashboard: ${luciConsoleLink(state.releaseChannel, 'engine')}'); + '\tPost-submit LUCI dashboard: ${luciConsoleLink(state.engine.candidateBranch, 'engine')}'); if (state.engine.cherrypicks.isNotEmpty) { buffer.writeln('${state.engine.cherrypicks.length} Engine Cherrypicks:'); for (final pb.Cherrypick cherrypick in state.engine.cherrypicks) { @@ -111,7 +109,7 @@ String presentState(pb.ConductorState state) { buffer.writeln('\tCurrent git HEAD: ${state.framework.currentGitHead}'); buffer.writeln('\tPath to checkout: ${state.framework.checkoutPath}'); buffer.writeln( - '\tPost-submit LUCI dashboard: ${luciConsoleLink(state.releaseChannel, 'flutter')}'); + '\tPost-submit LUCI dashboard: ${luciConsoleLink(state.framework.candidateBranch, 'flutter')}'); if (state.framework.cherrypicks.isNotEmpty) { buffer.writeln( '${state.framework.cherrypicks.length} Framework Cherrypicks:'); @@ -180,7 +178,7 @@ String phaseInstructions(pb.ConductorState state) { case ReleasePhase.VERIFY_ENGINE_CI: if (!requiresEnginePR(state)) { return 'You must verify engine CI has passed: ' - '${luciConsoleLink(state.releaseChannel, 'engine')}'; + '${luciConsoleLink(state.engine.candidateBranch, 'engine')}'; } // User's working branch was pushed to their mirror, but a PR needs to be // opened on GitHub. @@ -189,11 +187,12 @@ String phaseInstructions(pb.ConductorState state) { repoName: 'engine', state: state, ); + final String consoleLink = luciConsoleLink(state.engine.candidateBranch, 'engine'); return [ 'Your working branch ${state.engine.workingBranch} was pushed to your mirror.', 'You must now open a pull request at $newPrLink, verify pre-submit CI', 'builds on your engine pull request are successful, merge your pull request,', - 'validate post-submit CI, and then codesign the binaries on the merge commit.', + 'validate post-submit CI at $consoleLink.', ].join('\n'); case ReleasePhase.APPLY_FRAMEWORK_CHERRYPICKS: final List outstandingCherrypicks = @@ -232,7 +231,7 @@ String phaseInstructions(pb.ConductorState state) { 'pull request, validate post-submit CI.', ].join('\n'); case ReleasePhase.VERIFY_RELEASE: - return 'Release archive packages must be verified on cloud storage: ${luciConsoleLink(state.releaseChannel, 'packaging')}'; + return 'Release archive packages must be verified on cloud storage: ${luciConsoleLink(state.framework.candidateBranch, 'packaging')}'; case ReleasePhase.RELEASE_COMPLETED: if (state.releaseChannel == 'beta') { return [ diff --git a/dev/conductor/core/pubspec.yaml b/dev/conductor/core/pubspec.yaml index 121c736c1ac..07434a91591 100644 --- a/dev/conductor/core/pubspec.yaml +++ b/dev/conductor/core/pubspec.yaml @@ -4,7 +4,7 @@ description: Flutter Automated Release Tool publish_to: none environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: archive: 3.6.1 diff --git a/dev/conductor/core/test/next_test.dart b/dev/conductor/core/test/next_test.dart index 82933a474a6..dcdceed04d8 100644 --- a/dev/conductor/core/test/next_test.dart +++ b/dev/conductor/core/test/next_test.dart @@ -239,6 +239,7 @@ void main() { ..trunkRevision = 'abc123' ..state = pb.CherrypickState.PENDING ) + ..candidateBranch = 'flutter-1.0-candidate.0' ) ..currentPhase = ReleasePhase.VERIFY_ENGINE_CI ); diff --git a/dev/customer_testing/pubspec.yaml b/dev/customer_testing/pubspec.yaml index f3ff4e4ca19..753b3fcfa5f 100644 --- a/dev/customer_testing/pubspec.yaml +++ b/dev/customer_testing/pubspec.yaml @@ -2,7 +2,7 @@ name: customer_testing description: Tool to run the tests listed in the flutter/tests repository. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: args: 2.6.0 diff --git a/dev/devicelab/bin/tasks/android_release_builds_exclude_dev_dependencies_test.dart b/dev/devicelab/bin/tasks/android_release_builds_exclude_dev_dependencies_test.dart new file mode 100644 index 00000000000..c8e6e305300 --- /dev/null +++ b/dev/devicelab/bin/tasks/android_release_builds_exclude_dev_dependencies_test.dart @@ -0,0 +1,60 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter_devicelab/framework/apk_utils.dart'; +import 'package:flutter_devicelab/framework/framework.dart'; +import 'package:flutter_devicelab/framework/task_result.dart'; +import 'package:flutter_devicelab/framework/utils.dart'; +import 'package:path/path.dart' as path; + +Future main() async { + await task(() async { + try { + await runProjectTest((FlutterProject flutterProject) async { + // Create dev_dependency plugin to use for test. + final Directory tempDir = Directory.systemTemp.createTempSync('android_release_builds_exclude_dev_dependencies_test.'); + const String devDependencyPluginOrg = 'com.example.dev_dependency_plugin'; + await FlutterPluginProject.create(tempDir, 'dev_dependency_plugin', options: ['--platforms=android', '--org=$devDependencyPluginOrg']); + + // Add devDependencyPlugin as dependency of flutterProject. + await flutterProject.addPlugin('dev_dependency_plugin', options: ['--path', path.join(tempDir.path, 'dev_dependency_plugin')]); + + final List buildModesToTest = ['debug', 'profile', 'release']; + for (final String buildMode in buildModesToTest) { + section('APK does contain methods from dev dependency in $buildMode mode'); + + // Build APK in buildMode and check that devDependencyPlugin is included/excluded in the APK as expected. + await inDirectory(flutterProject.rootPath, () async { + await flutter('build', options: [ + 'apk', + '--$buildMode', + '--target-platform=android-arm', + ]); + + final File apk = File(path.join(flutterProject.rootPath, 'build', 'app', 'outputs', 'flutter-apk', 'app-debug.apk')); + if (!apk.existsSync()) { + throw TaskResult.failure("Expected ${apk.path} to exist, but it doesn't."); + } + + // We expect the APK to include the devDependencyPlugin except in release mode. + final bool isTestingReleaseMode = buildMode == 'release'; + final bool apkIncludesDevDependency = await checkApkContainsMethodsFromLibrary(apk, devDependencyPluginOrg); + final bool apkIncludesDevDependencyAsExpected = isTestingReleaseMode ? !apkIncludesDevDependency : apkIncludesDevDependency; + if (!apkIncludesDevDependencyAsExpected) { + return TaskResult.failure('Expected to${isTestingReleaseMode ? ' not' : ''} find dev_dependency_plugin in APK built with debug mode but did${isTestingReleaseMode ? '' : ' not'}.'); + } + }); + } + }); + return TaskResult.success(null); + } on TaskResult catch (taskResult) { + return taskResult; + } catch (e) { + return TaskResult.failure(e.toString()); + } + }); +} diff --git a/dev/devicelab/bin/tasks/build_aar_module_test.dart b/dev/devicelab/bin/tasks/build_aar_module_test.dart index c30639830d6..6232d25a9e5 100644 --- a/dev/devicelab/bin/tasks/build_aar_module_test.dart +++ b/dev/devicelab/bin/tasks/build_aar_module_test.dart @@ -10,8 +10,6 @@ import 'package:flutter_devicelab/framework/task_result.dart'; import 'package:flutter_devicelab/framework/utils.dart'; import 'package:path/path.dart' as path; -final String platformLineSep = Platform.isWindows ? '\r\n': '\n'; - /// Tests that AARs can be built on module projects. Future main() async { await task(() async { @@ -59,12 +57,12 @@ Future main() async { final File modulePubspec = File(path.join(projectDir.path, 'pubspec.yaml')); String content = modulePubspec.readAsStringSync(); content = content.replaceFirst( - '${platformLineSep}dependencies:$platformLineSep', - '${platformLineSep}dependencies:$platformLineSep' - ' plugin_with_android:$platformLineSep' - ' path: ../plugin_with_android$platformLineSep' - ' plugin_without_android:$platformLineSep' - ' path: ../plugin_without_android$platformLineSep' + '${Platform.lineTerminator}dependencies:${Platform.lineTerminator}', + '${Platform.lineTerminator}dependencies:${Platform.lineTerminator}' + ' plugin_with_android:${Platform.lineTerminator}' + ' path: ../plugin_with_android${Platform.lineTerminator}' + ' plugin_without_android:${Platform.lineTerminator}' + ' path: ../plugin_without_android${Platform.lineTerminator}' ); modulePubspec.writeAsStringSync(content, flush: true); diff --git a/dev/devicelab/bin/tasks/build_android_host_app_with_module_aar.dart b/dev/devicelab/bin/tasks/build_android_host_app_with_module_aar.dart index 0b1f16820fb..3865e4a0eba 100644 --- a/dev/devicelab/bin/tasks/build_android_host_app_with_module_aar.dart +++ b/dev/devicelab/bin/tasks/build_android_host_app_with_module_aar.dart @@ -17,7 +17,6 @@ final String gradlew = Platform.isWindows ? 'gradlew.bat' : 'gradlew'; final String gradlewExecutable = Platform.isWindows ? '.\\$gradlew' : './$gradlew'; final String fileReadWriteMode = Platform.isWindows ? 'rw-rw-rw-' : 'rw-r--r--'; -final String platformLineSep = Platform.isWindows ? '\r\n' : '\n'; /// Combines several TaskFunctions with trivial success value into one. TaskFunction combine(List tasks) { @@ -41,6 +40,8 @@ class ModuleTest { static const String buildTarget = 'module-gradle'; final String gradleVersion; + final StringBuffer stdout = StringBuffer(); + final StringBuffer stderr = StringBuffer(); Future call() async { section('Running: $buildTarget-$gradleVersion'); @@ -61,6 +62,8 @@ class ModuleTest { await flutter( 'create', options: ['--org', 'io.flutter.devicelab', '--template=module', 'hello'], + output: stdout, + stderr: stderr, ); }); @@ -69,6 +72,8 @@ class ModuleTest { await flutter( 'config', options: ['--enable-native-assets'], + output: stdout, + stderr: stderr, ); const String ffiPackageName = 'ffi_package'; @@ -79,14 +84,16 @@ class ModuleTest { final File pubspec = File(path.join(projectDir.path, 'pubspec.yaml')); String content = await pubspec.readAsString(); content = content.replaceFirst( - 'dependencies:$platformLineSep', - 'dependencies:$platformLineSep $ffiPackageName:$platformLineSep path: ..${Platform.pathSeparator}$ffiPackageName$platformLineSep', + 'dependencies:${Platform.lineTerminator}', + 'dependencies:${Platform.lineTerminator} $ffiPackageName:${Platform.lineTerminator} path: ..${Platform.pathSeparator}$ffiPackageName${Platform.lineTerminator}', ); await pubspec.writeAsString(content, flush: true); await inDirectory(projectDir, () async { await flutter( 'packages', options: ['get'], + output: stdout, + stderr: stderr, ); }); @@ -111,22 +118,24 @@ class ModuleTest { } content = content.replaceFirst( - '$platformLineSep # assets:$platformLineSep', - '$platformLineSep assets:$platformLineSep - assets/read-only.txt$platformLineSep', + '${Platform.lineTerminator} # assets:${Platform.lineTerminator}', + '${Platform.lineTerminator} assets:${Platform.lineTerminator} - assets/read-only.txt${Platform.lineTerminator}', ); await pubspec.writeAsString(content, flush: true); section('Add plugins'); content = content.replaceFirst( - '${platformLineSep}dependencies:$platformLineSep', - '${platformLineSep}dependencies:$platformLineSep', + '${Platform.lineTerminator}dependencies:${Platform.lineTerminator}', + '${Platform.lineTerminator}dependencies:${Platform.lineTerminator}', ); await pubspec.writeAsString(content, flush: true); await inDirectory(projectDir, () async { await flutter( 'packages', options: ['get'], + output: stdout, + stderr: stderr, ); }); @@ -162,6 +171,8 @@ class ModuleTest { await flutter( 'build', options: ['apk'], + output: stdout, + stderr: stderr, ); }); @@ -182,7 +193,11 @@ class ModuleTest { section('Clean build'); await inDirectory(projectDir, () async { - await flutter('clean'); + await flutter( + 'clean', + output: stdout, + stderr: stderr, + ); }); section('Make Android host app editable'); @@ -191,6 +206,8 @@ class ModuleTest { await flutter( 'make-host-app-editable', options: ['android'], + output: stdout, + stderr: stderr, ); }); @@ -200,6 +217,8 @@ class ModuleTest { await flutter( 'build', options: ['apk'], + output: stdout, + stderr: stderr, ); }); @@ -255,9 +274,6 @@ class ModuleTest { section(propertyContent); await gradleWrapperProperties.writeAsString(propertyContent, flush: true); - final File analyticsOutputFile = - File(path.join(tempDir.path, 'analytics.log')); - section('Build debug host APK'); await inDirectory(hostApp, () async { @@ -268,7 +284,7 @@ class ModuleTest { ['app:assembleDebug'], environment: { 'JAVA_HOME': javaHome, - 'FLUTTER_ANALYTICS_LOG_FILE': analyticsOutputFile.path, + 'FLUTTER_SUPPRESS_ANALYTICS': 'true', }, ); }); @@ -309,17 +325,6 @@ class ModuleTest { return TaskResult.failure("Debug host APK doesn't contain metadata: flutterProjectType = module "); } - final String analyticsOutput = analyticsOutputFile.readAsStringSync(); - if (!analyticsOutput.contains('cd24: android') - || !analyticsOutput.contains('cd25: true') - || !analyticsOutput.contains('viewName: assemble')) { - return TaskResult.failure( - 'Building outer app produced the following analytics: "$analyticsOutput" ' - 'but not the expected strings: "cd24: android", "cd25: true" and ' - '"viewName: assemble"' - ); - } - section('Check file access modes for read-only asset from Flutter module'); final String readonlyDebugAssetFilePath = path.joinAll([ @@ -351,7 +356,7 @@ class ModuleTest { ['app:assembleRelease'], environment: { 'JAVA_HOME': javaHome, - 'FLUTTER_ANALYTICS_LOG_FILE': analyticsOutputFile.path, + 'FLUTTER_SUPPRESS_ANALYTICS': 'true', }, ); }); @@ -435,6 +440,12 @@ class ModuleTest { return TaskResult.failure('Failed to make assets user-readable and writable'); } + section('Check for specific log errors.'); + final String finalStderr = stderr.toString(); + if (finalStderr.contains("You are applying Flutter's main Gradle plugin imperatively")) { + return TaskResult.failure('Applied the Flutter Gradle Plugin imperatively'); + } + return TaskResult.success(null); } on TaskResult catch (taskResult) { return taskResult; diff --git a/dev/devicelab/bin/tasks/build_android_host_app_with_module_source.dart b/dev/devicelab/bin/tasks/build_android_host_app_with_module_source.dart index 542ba31f8cc..9164fb193b1 100644 --- a/dev/devicelab/bin/tasks/build_android_host_app_with_module_source.dart +++ b/dev/devicelab/bin/tasks/build_android_host_app_with_module_source.dart @@ -17,7 +17,6 @@ final String gradlew = Platform.isWindows ? 'gradlew.bat' : 'gradlew'; final String gradlewExecutable = Platform.isWindows ? '.\\$gradlew' : './$gradlew'; final String fileReadWriteMode = Platform.isWindows ? 'rw-rw-rw-' : 'rw-r--r--'; -final String platformLineSep = Platform.isWindows ? '\r\n' : '\n'; /// Combines several TaskFunctions with trivial success value into one. TaskFunction combine(List tasks) { @@ -41,6 +40,8 @@ class ModuleTest { static const String buildTarget = 'module-gradle'; final String gradleVersion; + final StringBuffer stdout = StringBuffer(); + final StringBuffer stderr = StringBuffer(); Future call() async { section('Running: $buildTarget-$gradleVersion'); @@ -61,6 +62,8 @@ class ModuleTest { await flutter( 'create', options: ['--org', 'io.flutter.devicelab', '--template=module', 'hello'], + output: stdout, + stderr: stderr, ); }); @@ -69,6 +72,8 @@ class ModuleTest { await flutter( 'config', options: ['--enable-native-assets'], + output: stdout, + stderr: stderr, ); const String ffiPackageName = 'ffi_package'; @@ -79,14 +84,16 @@ class ModuleTest { final File pubspec = File(path.join(projectDir.path, 'pubspec.yaml')); String content = await pubspec.readAsString(); content = content.replaceFirst( - 'dependencies:$platformLineSep', - 'dependencies:$platformLineSep $ffiPackageName:$platformLineSep path: ..${Platform.pathSeparator}$ffiPackageName$platformLineSep', + 'dependencies:${Platform.lineTerminator}', + 'dependencies:${Platform.lineTerminator} $ffiPackageName:${Platform.lineTerminator} path: ..${Platform.pathSeparator}$ffiPackageName${Platform.lineTerminator}', ); await pubspec.writeAsString(content, flush: true); await inDirectory(projectDir, () async { await flutter( 'packages', options: ['get'], + output: stdout, + stderr: stderr, ); }); @@ -111,22 +118,24 @@ class ModuleTest { } content = content.replaceFirst( - '$platformLineSep # assets:$platformLineSep', - '$platformLineSep assets:$platformLineSep - assets/read-only.txt$platformLineSep', + '${Platform.lineTerminator} # assets:${Platform.lineTerminator}', + '${Platform.lineTerminator} assets:${Platform.lineTerminator} - assets/read-only.txt${Platform.lineTerminator}', ); await pubspec.writeAsString(content, flush: true); section('Add plugins'); content = content.replaceFirst( - '${platformLineSep}dependencies:$platformLineSep', - '${platformLineSep}dependencies:$platformLineSep', + '${Platform.lineTerminator}dependencies:${Platform.lineTerminator}', + '${Platform.lineTerminator}dependencies:${Platform.lineTerminator}', ); await pubspec.writeAsString(content, flush: true); await inDirectory(projectDir, () async { await flutter( 'packages', options: ['get'], + output: stdout, + stderr: stderr, ); }); @@ -136,6 +145,8 @@ class ModuleTest { await flutter( 'build', options: ['apk'], + output: stdout, + stderr: stderr, ); }); @@ -156,7 +167,11 @@ class ModuleTest { section('Clean build'); await inDirectory(projectDir, () async { - await flutter('clean'); + await flutter( + 'clean', + output: stdout, + stderr: stderr, + ); }); section('Make Android host app editable'); @@ -165,6 +180,8 @@ class ModuleTest { await flutter( 'make-host-app-editable', options: ['android'], + output: stdout, + stderr: stderr, ); }); @@ -174,6 +191,8 @@ class ModuleTest { await flutter( 'build', options: ['apk'], + output: stdout, + stderr: stderr, ); }); @@ -229,9 +248,6 @@ class ModuleTest { section(propertyContent); await gradleWrapperProperties.writeAsString(propertyContent, flush: true); - final File analyticsOutputFile = - File(path.join(tempDir.path, 'analytics.log')); - section('Build debug host APK'); await inDirectory(hostApp, () async { @@ -242,7 +258,7 @@ class ModuleTest { ['app:assembleDebug'], environment: { 'JAVA_HOME': javaHome, - 'FLUTTER_ANALYTICS_LOG_FILE': analyticsOutputFile.path, + 'FLUTTER_SUPPRESS_ANALYTICS': 'true', }, ); }); @@ -283,17 +299,6 @@ class ModuleTest { return TaskResult.failure("Debug host APK doesn't contain metadata: flutterProjectType = module "); } - final String analyticsOutput = analyticsOutputFile.readAsStringSync(); - if (!analyticsOutput.contains('cd24: android') - || !analyticsOutput.contains('cd25: true') - || !analyticsOutput.contains('viewName: assemble')) { - return TaskResult.failure( - 'Building outer app produced the following analytics: "$analyticsOutput" ' - 'but not the expected strings: "cd24: android", "cd25: true" and ' - '"viewName: assemble"' - ); - } - section('Check file access modes for read-only asset from Flutter module'); final String readonlyDebugAssetFilePath = path.joinAll([ @@ -326,7 +331,7 @@ class ModuleTest { ['app:assembleRelease'], environment: { 'JAVA_HOME': javaHome, - 'FLUTTER_ANALYTICS_LOG_FILE': analyticsOutputFile.path, + 'FLUTTER_SUPPRESS_ANALYTICS': 'true', }, ); }); @@ -411,6 +416,12 @@ class ModuleTest { return TaskResult.failure('Failed to make assets user-readable and writable'); } + section('Check for specific log errors.'); + final String finalStderr = stderr.toString(); + if (finalStderr.contains("You are applying Flutter's main Gradle plugin imperatively")) { + return TaskResult.failure('Applied the Flutter Gradle Plugin imperatively'); + } + return TaskResult.success(null); } on TaskResult catch (taskResult) { return taskResult; diff --git a/dev/devicelab/bin/tasks/gradle_desugar_classes_test.dart b/dev/devicelab/bin/tasks/gradle_desugar_classes_test.dart index ec6cec85adc..2d6062ed35c 100644 --- a/dev/devicelab/bin/tasks/gradle_desugar_classes_test.dart +++ b/dev/devicelab/bin/tasks/gradle_desugar_classes_test.dart @@ -16,7 +16,7 @@ Future main() async { await runProjectTest((FlutterProject flutterProject) async { section('APK contains plugin classes'); await flutterProject.setMinSdkVersion(20); - flutterProject.addPlugin('google_maps_flutter', value: '^2.2.1'); + await flutterProject.addPlugin('google_maps_flutter:^2.2.1'); await inDirectory(flutterProject.rootPath, () async { await flutter('build', options: [ diff --git a/dev/devicelab/bin/tasks/gradle_plugin_light_apk_test.dart b/dev/devicelab/bin/tasks/gradle_plugin_light_apk_test.dart index ee3519a39eb..bf66697bc90 100644 --- a/dev/devicelab/bin/tasks/gradle_plugin_light_apk_test.dart +++ b/dev/devicelab/bin/tasks/gradle_plugin_light_apk_test.dart @@ -210,8 +210,7 @@ Future main() async { }); section('Configure'); - project.addPlugin('plugin_under_test', - value: '$platformLineSep path: ${pluginDir.path}'); + await project.addPlugin('plugin_under_test', options: ['--path', pluginDir.path]); await project.addCustomBuildType('local', initWith: 'debug'); await project.getPackages(); @@ -229,7 +228,7 @@ Future main() async { section('gradlew assembleLocal (plugin with custom build type)'); await project.addCustomBuildType('local', initWith: 'debug'); section('Add plugin'); - project.addPlugin('path_provider'); + await project.addPlugin('path_provider'); await project.getPackages(); await project.runGradleTask('assembleLocal'); diff --git a/dev/devicelab/bin/tasks/module_custom_host_app_name_test.dart b/dev/devicelab/bin/tasks/module_custom_host_app_name_test.dart index 9cb5a637875..8466e49edbb 100644 --- a/dev/devicelab/bin/tasks/module_custom_host_app_name_test.dart +++ b/dev/devicelab/bin/tasks/module_custom_host_app_name_test.dart @@ -13,7 +13,6 @@ import 'package:path/path.dart' as path; final String gradlew = Platform.isWindows ? 'gradlew.bat' : 'gradlew'; final String gradlewExecutable = Platform.isWindows ? '.\\$gradlew' : './$gradlew'; final String fileReadWriteMode = Platform.isWindows ? 'rw-rw-rw-' : 'rw-r--r--'; -final String platformLineSep = Platform.isWindows ? '\r\n': '\n'; /// Tests that the Flutter module project template works and supports /// adding Flutter to an existing Android app. @@ -63,8 +62,8 @@ Future main() async { final File pubspec = File(path.join(projectDir.path, 'pubspec.yaml')); String content = await pubspec.readAsString(); content = content.replaceFirst( - '$platformLineSep # assets:$platformLineSep', - '$platformLineSep assets:$platformLineSep - assets/read-only.txt$platformLineSep', + '${Platform.lineTerminator} # assets:${Platform.lineTerminator}', + '${Platform.lineTerminator} assets:${Platform.lineTerminator} - assets/read-only.txt${Platform.lineTerminator}', ); await pubspec.writeAsString(content, flush: true); @@ -72,8 +71,8 @@ Future main() async { content = await pubspec.readAsString(); content = content.replaceFirst( - '${platformLineSep}dependencies:$platformLineSep', - '${platformLineSep}dependencies:$platformLineSep', + '${Platform.lineTerminator}dependencies:${Platform.lineTerminator}', + '${Platform.lineTerminator}dependencies:${Platform.lineTerminator}', ); await pubspec.writeAsString(content, flush: true); await inDirectory(projectDir, () async { @@ -193,8 +192,6 @@ Future main() async { Directory(path.join(hostApp.path, 'gradle', 'wrapper')), ); - final File analyticsOutputFile = File(path.join(tempDir.path, 'analytics.log')); - section('Build debug host APK'); await inDirectory(hostApp, () async { @@ -205,7 +202,7 @@ Future main() async { ['SampleApp:assembleDebug'], environment: { 'JAVA_HOME': javaHome, - 'FLUTTER_ANALYTICS_LOG_FILE': analyticsOutputFile.path, + 'FLUTTER_SUPPRESS_ANALYTICS': 'true', }, ); }); @@ -244,17 +241,6 @@ Future main() async { return TaskResult.failure("Debug host APK doesn't contain metadata: flutterProjectType = module "); } - final String analyticsOutput = analyticsOutputFile.readAsStringSync(); - if (!analyticsOutput.contains('cd24: android') - || !analyticsOutput.contains('cd25: true') - || !analyticsOutput.contains('viewName: assemble')) { - return TaskResult.failure( - 'Building outer app produced the following analytics: "$analyticsOutput" ' - 'but not the expected strings: "cd24: android", "cd25: true" and ' - '"viewName: assemble"' - ); - } - section('Check file access modes for read-only asset from Flutter module'); final String readonlyDebugAssetFilePath = path.joinAll([ @@ -286,7 +272,7 @@ Future main() async { ['SampleApp:assembleRelease'], environment: { 'JAVA_HOME': javaHome, - 'FLUTTER_ANALYTICS_LOG_FILE': analyticsOutputFile.path, + 'FLUTTER_SUPPRESS_ANALYTICS': 'true', }, ); }); diff --git a/dev/devicelab/bin/tasks/module_test_ios.dart b/dev/devicelab/bin/tasks/module_test_ios.dart index 98865c92360..dfdad784713 100644 --- a/dev/devicelab/bin/tasks/module_test_ios.dart +++ b/dev/devicelab/bin/tasks/module_test_ios.dart @@ -271,7 +271,6 @@ dependencies: objectiveCHostApp, ); - final File objectiveCAnalyticsOutputFile = File(path.join(tempDir.path, 'analytics-objc.log')); final Directory objectiveCBuildDirectory = Directory(path.join(tempDir.path, 'build-objc')); await inDirectory(objectiveCHostApp, () async { @@ -374,7 +373,7 @@ end 'COMPILER_INDEX_STORE_ENABLE=NO', ], environment: { - 'FLUTTER_ANALYTICS_LOG_FILE': objectiveCAnalyticsOutputFile.path, + 'FLUTTER_SUPPRESS_ANALYTICS': 'true', }, ); }); @@ -435,18 +434,6 @@ end } }); - section('Check that the host build sends the correct analytics'); - - final String objectiveCAnalyticsOutput = objectiveCAnalyticsOutputFile.readAsStringSync(); - if (!objectiveCAnalyticsOutput.contains('cd24: ios') - || !objectiveCAnalyticsOutput.contains('cd25: true') - || !objectiveCAnalyticsOutput.contains('viewName: assemble')) { - return TaskResult.failure( - 'Building outer Objective-C app produced the following analytics: "$objectiveCAnalyticsOutput" ' - 'but not the expected strings: "cd24: ios", "cd25: true", "viewName: assemble"' - ); - } - section('Archive iOS Objective-C host app'); await inDirectory(objectiveCHostApp, () async { @@ -470,7 +457,7 @@ end 'archive', ], environment: { - 'FLUTTER_ANALYTICS_LOG_FILE': objectiveCAnalyticsOutputFile.path, + 'FLUTTER_SUPPRESS_ANALYTICS': 'true', }, ); diff --git a/dev/devicelab/bin/tasks/plugin_dependencies_test.dart b/dev/devicelab/bin/tasks/plugin_dependencies_test.dart index baae2f6bf63..dd667750277 100644 --- a/dev/devicelab/bin/tasks/plugin_dependencies_test.dart +++ b/dev/devicelab/bin/tasks/plugin_dependencies_test.dart @@ -11,8 +11,6 @@ import 'package:flutter_devicelab/framework/task_result.dart'; import 'package:flutter_devicelab/framework/utils.dart'; import 'package:path/path.dart' as path; -final String platformLineSep = Platform.isWindows ? '\r\n': '\n'; - /// Tests that a plugin A can depend on platform code from a plugin B /// as long as plugin B is defined as a pub dependency of plugin A. /// @@ -102,7 +100,7 @@ dependencies: sdk: flutter environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 flutter: ">=1.5.0" ''', flush: true); @@ -154,14 +152,14 @@ public class DummyPluginBClass { final File pluginApubspec = File(path.join(pluginADirectory.path, 'pubspec.yaml')); String pluginApubspecContent = await pluginApubspec.readAsString(); pluginApubspecContent = pluginApubspecContent.replaceFirst( - '${platformLineSep}dependencies:$platformLineSep', - '${platformLineSep}dependencies:$platformLineSep' - ' plugin_b:$platformLineSep' - ' path: ${pluginBDirectory.path}$platformLineSep' - ' plugin_c:$platformLineSep' - ' path: ${pluginCDirectory.path}$platformLineSep' - ' plugin_d:$platformLineSep' - ' path: ${pluginDDirectory.path}$platformLineSep', + '${Platform.lineTerminator}dependencies:${Platform.lineTerminator}', + '${Platform.lineTerminator}dependencies:${Platform.lineTerminator}' + ' plugin_b:${Platform.lineTerminator}' + ' path: ${pluginBDirectory.path}${Platform.lineTerminator}' + ' plugin_c:${Platform.lineTerminator}' + ' path: ${pluginCDirectory.path}${Platform.lineTerminator}' + ' plugin_d:${Platform.lineTerminator}' + ' path: ${pluginDDirectory.path}${Platform.lineTerminator}', ); await pluginApubspec.writeAsString(pluginApubspecContent, flush: true); @@ -210,7 +208,7 @@ public class DummyPluginAClass { final String flutterPluginsDependenciesFileContent = flutterPluginsDependenciesFile.readAsStringSync(); final Map jsonContent = json.decode(flutterPluginsDependenciesFileContent) as Map; - final bool swiftPackageManagerEnabled = jsonContent['swift_package_manager_enabled'] as bool? ?? false; + final Map? swiftPackageManagerJson = jsonContent['swift_package_manager_enabled'] as Map?; // Verify the dependencyGraph object is valid. The rest of the contents of this file are not relevant to the // dependency graph and are tested by unit tests. @@ -304,6 +302,18 @@ public class DummyPluginAClass { return TaskResult.failure('Failed to build plugin A example iOS app'); } + final bool? swiftPackageManagerEnabled = swiftPackageManagerJson?['ios'] as bool?; + if (swiftPackageManagerEnabled == null) { + return TaskResult.failure( + '${flutterPluginsDependenciesFile.path} is missing the ' + '"swift_package_manager_enabled" > "ios" property.\n' + '\n' + '.flutter_plugin_dependencies content:\n' + '\n' + '$flutterPluginsDependenciesFileContent', + ); + } + if (swiftPackageManagerEnabled) { // Check plugins are built statically if using SwiftPM. final String executable = path.join(appBundle.path, 'Runner'); diff --git a/dev/devicelab/bin/tasks/web_benchmarks_canvaskit.dart b/dev/devicelab/bin/tasks/web_benchmarks_canvaskit.dart index e420fc3389a..8c0c319ffa1 100644 --- a/dev/devicelab/bin/tasks/web_benchmarks_canvaskit.dart +++ b/dev/devicelab/bin/tasks/web_benchmarks_canvaskit.dart @@ -9,7 +9,6 @@ import 'package:flutter_devicelab/tasks/web_benchmarks.dart'; Future main() async { await task(() async { return runWebBenchmark(( - webRenderer: 'canvaskit', useWasm: false, forceSingleThreadedSkwasm: false, )); diff --git a/dev/devicelab/bin/tasks/web_benchmarks_html.dart b/dev/devicelab/bin/tasks/web_benchmarks_html.dart deleted file mode 100644 index a5a7e39db37..00000000000 --- a/dev/devicelab/bin/tasks/web_benchmarks_html.dart +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2014 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter_devicelab/framework/framework.dart'; -import 'package:flutter_devicelab/tasks/web_benchmarks.dart'; - -/// Runs all Web benchmarks using the HTML rendering backend. -Future main() async { - await task(() async { - return runWebBenchmark(( - webRenderer: 'html', - useWasm: false, - forceSingleThreadedSkwasm: false, - )); - }); -} diff --git a/dev/devicelab/bin/tasks/web_benchmarks_skwasm.dart b/dev/devicelab/bin/tasks/web_benchmarks_skwasm.dart index f729c6d48af..cf26d6db48e 100644 --- a/dev/devicelab/bin/tasks/web_benchmarks_skwasm.dart +++ b/dev/devicelab/bin/tasks/web_benchmarks_skwasm.dart @@ -9,7 +9,6 @@ import 'package:flutter_devicelab/tasks/web_benchmarks.dart'; Future main() async { await task(() async { return runWebBenchmark(( - webRenderer: 'skwasm', useWasm: true, forceSingleThreadedSkwasm: false, )); diff --git a/dev/devicelab/bin/tasks/web_benchmarks_skwasm_st.dart b/dev/devicelab/bin/tasks/web_benchmarks_skwasm_st.dart index 71698683ed5..a84ab93eb5c 100644 --- a/dev/devicelab/bin/tasks/web_benchmarks_skwasm_st.dart +++ b/dev/devicelab/bin/tasks/web_benchmarks_skwasm_st.dart @@ -9,7 +9,6 @@ import 'package:flutter_devicelab/tasks/web_benchmarks.dart'; Future main() async { await task(() async { return runWebBenchmark(( - webRenderer: 'skwasm', useWasm: true, forceSingleThreadedSkwasm: true, )); diff --git a/dev/devicelab/lib/framework/apk_utils.dart b/dev/devicelab/lib/framework/apk_utils.dart index e9ebfea319c..c2aa90e4dc1 100644 --- a/dev/devicelab/lib/framework/apk_utils.dart +++ b/dev/devicelab/lib/framework/apk_utils.dart @@ -9,8 +9,6 @@ import 'package:path/path.dart' as path; import 'task_result.dart'; import 'utils.dart'; -final String platformLineSep = Platform.isWindows ? '\r\n' : '\n'; - final List flutterAssets = [ 'assets/flutter_assets/AssetManifest.json', 'assets/flutter_assets/NOTICES.Z', @@ -194,6 +192,17 @@ class ApkExtractor { _extracted = true; } + /// Returns true if APK contains classes from library with given [libraryName]. + Future containsLibrary(String libraryName) async { + await _extractDex(); + for (final String className in _classes) { + if (className.startsWith(libraryName)) { + return true; + } + } + return false; + } + /// Returns true if the APK contains a given class. Future containsClass(String className) async { await _extractDex(); @@ -220,6 +229,14 @@ Future getAndroidManifest(String apk) async { ); } +/// Checks that the [apk] includes any classes from a particularly library with +/// given [libraryName] in the [apk] and returns true if so, false otherwise. +Future checkApkContainsMethodsFromLibrary(File apk, String libraryName) async { + final ApkExtractor extractor = ApkExtractor(apk); + final bool apkContainsMethodsFromLibrary = await extractor.containsLibrary(libraryName); + return apkContainsMethodsFromLibrary; +} + /// Checks that the classes are contained in the APK, throws otherwise. Future checkApkContainsClasses(File apk, List classes) async { final ApkExtractor extractor = ApkExtractor(apk); @@ -274,16 +291,17 @@ android { } /// Adds a plugin to the pubspec. - /// In pubspec, each dependency is expressed as key, value pair joined by a colon `:`. - /// such as `plugin_a`:`^0.0.1` or `plugin_a`:`\npath: /some/path`. - void addPlugin(String plugin, { String value = '' }) { - final File pubspec = File(path.join(rootPath, 'pubspec.yaml')); - String content = pubspec.readAsStringSync(); - content = content.replaceFirst( - '${platformLineSep}dependencies:$platformLineSep', - '${platformLineSep}dependencies:$platformLineSep $plugin: $value$platformLineSep', - ); - pubspec.writeAsStringSync(content, flush: true); + /// + /// If a particular version of the [plugin] is desired, it should be included + /// in the name as it would be in the `flutter pub add` command, e.g. + /// `google_maps_flutter:^2.2.1`. + /// + /// Include all other desired options for running `flutter pub add` to + /// [options], e.g. `['--path', 'path/to/plugin']`. + Future addPlugin(String plugin, {List options = const []}) async { + await inDirectory(Directory(rootPath), () async { + await flutter('pub', options: ['add', plugin, ...options]); + }); } Future setMinSdkVersion(int sdkVersion) async { @@ -336,7 +354,7 @@ android { path.join(parent.path, 'hello', 'pubspec.yaml') ); final String contents = pubspec.readAsStringSync(); - final String newContents = contents.replaceFirst('${platformLineSep}flutter:$platformLineSep', ''' + final String newContents = contents.replaceFirst('${Platform.lineTerminator}flutter:${Platform.lineTerminator}', ''' flutter: assets: @@ -369,9 +387,9 @@ class FlutterPluginProject { final Directory parent; final String name; - static Future create(Directory directory, String name) async { + static Future create(Directory directory, String name, {List options = const ['--platforms=ios,android']}) async { await inDirectory(directory, () async { - await flutter('create', options: ['--template=plugin', '--platforms=ios,android', name]); + await flutter('create', options: ['--template=plugin', ...options, name]); }); return FlutterPluginProject(directory, name); } diff --git a/dev/devicelab/lib/framework/utils.dart b/dev/devicelab/lib/framework/utils.dart index 384d8bb0444..63135acf427 100644 --- a/dev/devicelab/lib/framework/utils.dart +++ b/dev/devicelab/lib/framework/utils.dart @@ -514,12 +514,21 @@ Future flutter(String command, { // DevToolsMemoryTest in perf_tests.dart. Map? environment, String? workingDirectory, + StringBuffer? output, // if not null, the stdout will be written here + StringBuffer? stderr, // if not null, the stderr will be written here }) async { final List args = _flutterCommandArgs( command, options, driveWithDds: driveWithDds, ); - final int exitCode = await exec(path.join(flutterDirectory.path, 'bin', 'flutter'), args, - canFail: canFail, environment: environment, workingDirectory: workingDirectory); + final int exitCode = await exec( + path.join(flutterDirectory.path, 'bin', 'flutter'), + args, + canFail: canFail, + environment: environment, + workingDirectory: workingDirectory, + output: output, + stderr: stderr, + ); if (exitCode != 0 && !canFail) { await _flutterScreenshot(workingDirectory: workingDirectory); diff --git a/dev/devicelab/lib/tasks/perf_tests.dart b/dev/devicelab/lib/tasks/perf_tests.dart index 8d7fc07ece8..bd08e664b90 100644 --- a/dev/devicelab/lib/tasks/perf_tests.dart +++ b/dev/devicelab/lib/tasks/perf_tests.dart @@ -2042,7 +2042,7 @@ class MemoryTest { await receivedNextMessage; } - /// Taps the application and looks for acknowldgement. + /// Taps the application and looks for acknowledgement. /// /// This is used by several tests to ensure scrolling gestures are installed. Future tapNotification() async { diff --git a/dev/devicelab/lib/tasks/web_benchmarks.dart b/dev/devicelab/lib/tasks/web_benchmarks.dart index 2368a38720b..cf5cb8d54c5 100644 --- a/dev/devicelab/lib/tasks/web_benchmarks.dart +++ b/dev/devicelab/lib/tasks/web_benchmarks.dart @@ -21,7 +21,6 @@ const int benchmarkServerPort = 9999; const int chromeDebugPort = 10000; typedef WebBenchmarkOptions = ({ - String webRenderer, bool useWasm, bool forceSingleThreadedSkwasm, }); @@ -41,7 +40,6 @@ Future runWebBenchmark(WebBenchmarkOptions benchmarkOptions) async { '--no-strip-wasm', ], '--dart-define=FLUTTER_WEB_ENABLE_PROFILING=true', - if (!benchmarkOptions.useWasm) '--web-renderer=${benchmarkOptions.webRenderer}', '--profile', '--no-web-resources-cdn', '-t', @@ -175,10 +173,10 @@ Future runWebBenchmark(WebBenchmarkOptions benchmarkOptions) async { } final String webRendererName; - if (benchmarkOptions.useWasm && benchmarkOptions.forceSingleThreadedSkwasm) { - webRendererName = 'skwasm_st'; + if (benchmarkOptions.useWasm) { + webRendererName = benchmarkOptions.forceSingleThreadedSkwasm ? 'skwasm_st' : 'skwasm'; } else { - webRendererName = benchmarkOptions.webRenderer; + webRendererName = 'canvaskit'; } final String namespace = '$benchmarkName.$webRendererName'; final List scoreKeys = List.from(profile['scoreKeys'] as List); diff --git a/dev/devicelab/pubspec.yaml b/dev/devicelab/pubspec.yaml index 51b726ab0ab..b6215f717bb 100644 --- a/dev/devicelab/pubspec.yaml +++ b/dev/devicelab/pubspec.yaml @@ -3,7 +3,7 @@ description: Flutter continuous integration performance and correctness tests. homepage: https://github.com/flutter/flutter environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: archive: 3.6.1 diff --git a/dev/docs/platform_integration/pubspec.yaml b/dev/docs/platform_integration/pubspec.yaml index ebe28969f05..8b6820cd785 100644 --- a/dev/docs/platform_integration/pubspec.yaml +++ b/dev/docs/platform_integration/pubspec.yaml @@ -1,4 +1,4 @@ name: platform_integration environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 diff --git a/dev/docs/renderers/pubspec.yaml b/dev/docs/renderers/pubspec.yaml index 76bdb8ce03b..a8941463556 100644 --- a/dev/docs/renderers/pubspec.yaml +++ b/dev/docs/renderers/pubspec.yaml @@ -1,4 +1,4 @@ name: renderers environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 diff --git a/dev/forbidden_from_release_tests/pubspec.yaml b/dev/forbidden_from_release_tests/pubspec.yaml index 024b68756b7..897a752f07d 100644 --- a/dev/forbidden_from_release_tests/pubspec.yaml +++ b/dev/forbidden_from_release_tests/pubspec.yaml @@ -2,7 +2,7 @@ name: forbidden_from_release_tests publish_to: 'none' environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: args: 2.6.0 diff --git a/dev/integration_tests/abstract_method_smoke_test/android/app/build.gradle b/dev/integration_tests/abstract_method_smoke_test/android/app/build.gradle deleted file mode 100644 index 7171eb700d4..00000000000 --- a/dev/integration_tests/abstract_method_smoke_test/android/app/build.gradle +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2014 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. - -plugins { - id "com.android.application" - id "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 = "com.example.abstract_method_smoke_test" - compileSdk flutter.compileSdkVersion - - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 - } - - kotlinOptions { - jvmTarget = '1.8' - } - - sourceSets { - main.java.srcDirs += 'src/main/kotlin' - } - - defaultConfig { - // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). - applicationId "com.example.abstract_method_smoke_test" - minSdkVersion 21 - targetSdkVersion flutter.targetSdkVersion - versionCode flutterVersionCode.toInteger() - versionName flutterVersionName - } - - buildTypes { - release { - signingConfig signingConfigs.debug - } - } -} - -flutter { - source '../..' -} - -dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.7.10" -} diff --git a/dev/integration_tests/abstract_method_smoke_test/android/app/src/debug/AndroidManifest.xml b/dev/integration_tests/abstract_method_smoke_test/android/app/src/debug/AndroidManifest.xml deleted file mode 100644 index 236efb914bf..00000000000 --- a/dev/integration_tests/abstract_method_smoke_test/android/app/src/debug/AndroidManifest.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - diff --git a/dev/integration_tests/abstract_method_smoke_test/android/app/src/main/AndroidManifest.xml b/dev/integration_tests/abstract_method_smoke_test/android/app/src/main/AndroidManifest.xml deleted file mode 100644 index 6ca5d4667d5..00000000000 --- a/dev/integration_tests/abstract_method_smoke_test/android/app/src/main/AndroidManifest.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/dev/integration_tests/abstract_method_smoke_test/android/app/src/main/kotlin/com/example/abstract_method_smoke_test/MainActivity.kt b/dev/integration_tests/abstract_method_smoke_test/android/app/src/main/kotlin/com/example/abstract_method_smoke_test/MainActivity.kt deleted file mode 100644 index b241e2b6d29..00000000000 --- a/dev/integration_tests/abstract_method_smoke_test/android/app/src/main/kotlin/com/example/abstract_method_smoke_test/MainActivity.kt +++ /dev/null @@ -1,72 +0,0 @@ -package com.example.abstract_method_smoke_test - -import android.content.Context -import android.graphics.Color -import android.view.View -import android.view.inputmethod.InputMethodManager -import androidx.annotation.NonNull -import io.flutter.embedding.android.FlutterActivity -import io.flutter.embedding.engine.FlutterEngine -import io.flutter.embedding.engine.plugins.shim.ShimPluginRegistry -import io.flutter.plugin.common.MethodChannel -import io.flutter.plugin.common.StandardMessageCodec -import io.flutter.plugin.platform.PlatformView -import io.flutter.plugin.platform.PlatformViewFactory -import io.flutter.plugins.GeneratedPluginRegistrant - -class MainActivity : FlutterActivity() { - class SimplePlatformView(context: Context) : PlatformView { - private val view: View = View(context) - - init { - view.setBackgroundColor(Color.CYAN) - } - - override fun dispose() {} - - override fun getView(): View { - return view - } - } - - override fun configureFlutterEngine( - @NonNull flutterEngine: FlutterEngine - ) { - GeneratedPluginRegistrant.registerWith(flutterEngine) - - val shimPluginRegistry = ShimPluginRegistry(flutterEngine) - shimPluginRegistry.registrarFor("com.example.abstract_method_smoke_test") - .platformViewRegistry() - .registerViewFactory( - "simple", - object : PlatformViewFactory(StandardMessageCodec.INSTANCE) { - override fun create( - context: Context?, - viewId: Int, - args: Any? - ): PlatformView { - return SimplePlatformView(this@MainActivity) - } - } - ) - - // Triggers the Android keyboard, which causes the resize of the Flutter view. - // We need to wait for the app to complete. - MethodChannel(flutterEngine.getDartExecutor(), "com.example.abstract_method_smoke_test") - .setMethodCallHandler { _, result -> - toggleInput() - result.success(null) - } - } - - override fun onPause() { - // Hide the input when the app is closed. - toggleInput() - super.onPause() - } - - private fun toggleInput() { - val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager - imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0) - } -} diff --git a/dev/integration_tests/abstract_method_smoke_test/android/app/src/main/res/drawable/launch_background.xml b/dev/integration_tests/abstract_method_smoke_test/android/app/src/main/res/drawable/launch_background.xml deleted file mode 100644 index bb6811b2ee1..00000000000 --- a/dev/integration_tests/abstract_method_smoke_test/android/app/src/main/res/drawable/launch_background.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - diff --git a/dev/integration_tests/abstract_method_smoke_test/android/app/src/main/res/values/styles.xml b/dev/integration_tests/abstract_method_smoke_test/android/app/src/main/res/values/styles.xml deleted file mode 100644 index 223593b1718..00000000000 --- a/dev/integration_tests/abstract_method_smoke_test/android/app/src/main/res/values/styles.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - diff --git a/dev/integration_tests/abstract_method_smoke_test/android/app/src/profile/AndroidManifest.xml b/dev/integration_tests/abstract_method_smoke_test/android/app/src/profile/AndroidManifest.xml deleted file mode 100644 index 236efb914bf..00000000000 --- a/dev/integration_tests/abstract_method_smoke_test/android/app/src/profile/AndroidManifest.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - diff --git a/dev/integration_tests/abstract_method_smoke_test/android/build.gradle b/dev/integration_tests/abstract_method_smoke_test/android/build.gradle deleted file mode 100644 index bedac9d2d4d..00000000000 --- a/dev/integration_tests/abstract_method_smoke_test/android/build.gradle +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2014 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. - -// This file is auto generated. -// To update all the build.gradle files in the Flutter repo, -// See dev/tools/bin/generate_gradle_lockfiles.dart. - -allprojects { - repositories { - google() - mavenCentral() - } -} - -rootProject.buildDir = '../build' - -subprojects { - project.buildDir = "${rootProject.buildDir}/${project.name}" -} -subprojects { - project.evaluationDependsOn(':app') - dependencyLocking { - ignoredDependencies.add('io.flutter:*') - lockFile = file("${rootProject.projectDir}/project-${project.name}.lockfile") - if (!project.hasProperty('local-engine-repo')) { - lockAllConfigurations() - } - } -} - -tasks.register("clean", Delete) { - delete rootProject.buildDir -} diff --git a/dev/integration_tests/abstract_method_smoke_test/android/buildscript-gradle.lockfile b/dev/integration_tests/abstract_method_smoke_test/android/buildscript-gradle.lockfile deleted file mode 100644 index 291d301d24c..00000000000 --- a/dev/integration_tests/abstract_method_smoke_test/android/buildscript-gradle.lockfile +++ /dev/null @@ -1,153 +0,0 @@ -# This is a Gradle generated file for dependency locking. -# Manual edits can break the build and are not advised. -# This file is expected to be part of source control. -androidx.databinding:databinding-common:8.7.0=classpath -androidx.databinding:databinding-compiler-common:8.7.0=classpath -com.android.application:com.android.application.gradle.plugin:8.7.0=classpath -com.android.databinding:baseLibrary:8.7.0=classpath -com.android.tools.analytics-library:crash:31.7.0=classpath -com.android.tools.analytics-library:protos:31.7.0=classpath -com.android.tools.analytics-library:shared:31.7.0=classpath -com.android.tools.analytics-library:tracker:31.7.0=classpath -com.android.tools.build.jetifier:jetifier-core:1.0.0-beta10=classpath -com.android.tools.build.jetifier:jetifier-processor:1.0.0-beta10=classpath -com.android.tools.build:aapt2-proto:8.7.0-12006047=classpath -com.android.tools.build:aaptcompiler:8.7.0=classpath -com.android.tools.build:apksig:8.7.0=classpath -com.android.tools.build:apkzlib:8.7.0=classpath -com.android.tools.build:builder-model:8.7.0=classpath -com.android.tools.build:builder-test-api:8.7.0=classpath -com.android.tools.build:builder:8.7.0=classpath -com.android.tools.build:bundletool:1.17.1=classpath -com.android.tools.build:gradle-api:8.7.0=classpath -com.android.tools.build:gradle-settings-api:8.7.0=classpath -com.android.tools.build:gradle:8.7.0=classpath -com.android.tools.build:manifest-merger:31.7.0=classpath -com.android.tools.build:transform-api:2.0.0-deprecated-use-gradle-api=classpath -com.android.tools.ddms:ddmlib:31.7.0=classpath -com.android.tools.layoutlib:layoutlib-api:31.7.0=classpath -com.android.tools.lint:lint-model:31.7.0=classpath -com.android.tools.lint:lint-typedef-remover:31.7.0=classpath -com.android.tools.utp:android-device-provider-ddmlib-proto:31.7.0=classpath -com.android.tools.utp:android-device-provider-gradle-proto:31.7.0=classpath -com.android.tools.utp:android-device-provider-profile-proto:31.7.0=classpath -com.android.tools.utp:android-test-plugin-host-additional-test-output-proto:31.7.0=classpath -com.android.tools.utp:android-test-plugin-host-apk-installer-proto:31.7.0=classpath -com.android.tools.utp:android-test-plugin-host-coverage-proto:31.7.0=classpath -com.android.tools.utp:android-test-plugin-host-emulator-control-proto:31.7.0=classpath -com.android.tools.utp:android-test-plugin-host-logcat-proto:31.7.0=classpath -com.android.tools.utp:android-test-plugin-host-retention-proto:31.7.0=classpath -com.android.tools.utp:android-test-plugin-result-listener-gradle-proto:31.7.0=classpath -com.android.tools:annotations:31.7.0=classpath -com.android.tools:common:31.7.0=classpath -com.android.tools:dvlib:31.7.0=classpath -com.android.tools:repository:31.7.0=classpath -com.android.tools:sdk-common:31.7.0=classpath -com.android.tools:sdklib:31.7.0=classpath -com.android:signflinger:8.7.0=classpath -com.android:zipflinger:8.7.0=classpath -com.google.android:annotations:4.1.1.4=classpath -com.google.api.grpc:proto-google-common-protos:2.17.0=classpath -com.google.auto.value:auto-value-annotations:1.6.2=classpath -com.google.code.findbugs:jsr305:3.0.2=classpath -com.google.code.gson:gson:2.10.1=classpath -com.google.crypto.tink:tink:1.7.0=classpath -com.google.dagger:dagger:2.28.3=classpath -com.google.errorprone:error_prone_annotations:2.18.0=classpath -com.google.flatbuffers:flatbuffers-java:1.12.0=classpath -com.google.guava:failureaccess:1.0.1=classpath -com.google.guava:guava:32.0.1-jre=classpath -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=classpath -com.google.j2objc:j2objc-annotations:2.8=classpath -com.google.jimfs:jimfs:1.1=classpath -com.google.protobuf:protobuf-java-util:3.22.3=classpath -com.google.protobuf:protobuf-java:3.22.3=classpath -com.google.testing.platform:core-proto:0.0.9-alpha02=classpath -com.googlecode.juniversalchardet:juniversalchardet:1.0.3=classpath -com.squareup:javapoet:1.10.0=classpath -com.squareup:javawriter:2.5.0=classpath -com.sun.activation:javax.activation:1.2.0=classpath -com.sun.istack:istack-commons-runtime:3.0.8=classpath -com.sun.xml.fastinfoset:FastInfoset:1.2.16=classpath -commons-codec:commons-codec:1.11=classpath -commons-io:commons-io:2.13.0=classpath -commons-logging:commons-logging:1.2=classpath -io.grpc:grpc-api:1.57.0=classpath -io.grpc:grpc-context:1.57.0=classpath -io.grpc:grpc-core:1.57.0=classpath -io.grpc:grpc-netty:1.57.0=classpath -io.grpc:grpc-protobuf-lite:1.57.0=classpath -io.grpc:grpc-protobuf:1.57.0=classpath -io.grpc:grpc-stub:1.57.0=classpath -io.netty:netty-buffer:4.1.93.Final=classpath -io.netty:netty-codec-http2:4.1.93.Final=classpath -io.netty:netty-codec-http:4.1.93.Final=classpath -io.netty:netty-codec-socks:4.1.93.Final=classpath -io.netty:netty-codec:4.1.93.Final=classpath -io.netty:netty-common:4.1.93.Final=classpath -io.netty:netty-handler-proxy:4.1.93.Final=classpath -io.netty:netty-handler:4.1.93.Final=classpath -io.netty:netty-resolver:4.1.93.Final=classpath -io.netty:netty-transport-native-unix-common:4.1.93.Final=classpath -io.netty:netty-transport:4.1.93.Final=classpath -io.perfmark:perfmark-api:0.26.0=classpath -jakarta.activation:jakarta.activation-api:1.2.1=classpath -jakarta.xml.bind:jakarta.xml.bind-api:2.3.2=classpath -javax.annotation:javax.annotation-api:1.3.2=classpath -javax.inject:javax.inject:1=classpath -net.java.dev.jna:jna-platform:5.6.0=classpath -net.java.dev.jna:jna:5.6.0=classpath -net.sf.jopt-simple:jopt-simple:4.9=classpath -net.sf.kxml:kxml2:2.3.0=classpath -org.apache.commons:commons-compress:1.21=classpath -org.apache.httpcomponents:httpclient:4.5.14=classpath -org.apache.httpcomponents:httpcore:4.4.16=classpath -org.apache.httpcomponents:httpmime:4.5.6=classpath -org.bitbucket.b_c:jose4j:0.9.5=classpath -org.bouncycastle:bcpkix-jdk18on:1.77=classpath -org.bouncycastle:bcprov-jdk18on:1.77=classpath -org.bouncycastle:bcutil-jdk18on:1.77=classpath -org.checkerframework:checker-qual:3.33.0=classpath -org.codehaus.mojo:animal-sniffer-annotations:1.23=classpath -org.glassfish.jaxb:jaxb-runtime:2.3.2=classpath -org.glassfish.jaxb:txw2:2.3.2=classpath -org.jdom:jdom2:2.0.6=classpath -org.jetbrains.intellij.deps:trove4j:1.0.20200330=classpath -org.jetbrains.kotlin.android:org.jetbrains.kotlin.android.gradle.plugin:1.8.10=classpath -org.jetbrains.kotlin:kotlin-android-extensions:1.8.10=classpath -org.jetbrains.kotlin:kotlin-annotation-processing-gradle:1.8.10=classpath -org.jetbrains.kotlin:kotlin-build-common:1.8.10=classpath -org.jetbrains.kotlin:kotlin-compiler-embeddable:1.8.10=classpath -org.jetbrains.kotlin:kotlin-compiler-runner:1.8.10=classpath -org.jetbrains.kotlin:kotlin-daemon-client:1.8.10=classpath -org.jetbrains.kotlin:kotlin-daemon-embeddable:1.8.10=classpath -org.jetbrains.kotlin:kotlin-gradle-plugin-api:1.8.10=classpath -org.jetbrains.kotlin:kotlin-gradle-plugin-idea-proto:1.8.10=classpath -org.jetbrains.kotlin:kotlin-gradle-plugin-idea:1.8.10=classpath -org.jetbrains.kotlin:kotlin-gradle-plugin-model:1.8.10=classpath -org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.10=classpath -org.jetbrains.kotlin:kotlin-klib-commonizer-api:1.8.10=classpath -org.jetbrains.kotlin:kotlin-native-utils:1.8.10=classpath -org.jetbrains.kotlin:kotlin-project-model:1.8.10=classpath -org.jetbrains.kotlin:kotlin-reflect:1.9.20=classpath -org.jetbrains.kotlin:kotlin-scripting-common:1.8.10=classpath -org.jetbrains.kotlin:kotlin-scripting-compiler-embeddable:1.8.10=classpath -org.jetbrains.kotlin:kotlin-scripting-compiler-impl-embeddable:1.8.10=classpath -org.jetbrains.kotlin:kotlin-scripting-jvm:1.8.10=classpath -org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.9.20=classpath -org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.9.20=classpath -org.jetbrains.kotlin:kotlin-stdlib:1.9.20=classpath -org.jetbrains.kotlin:kotlin-tooling-core:1.8.10=classpath -org.jetbrains.kotlin:kotlin-util-io:1.8.10=classpath -org.jetbrains.kotlin:kotlin-util-klib:1.8.10=classpath -org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.0=classpath -org.jetbrains:annotations:23.0.0=classpath -org.jvnet.staxex:stax-ex:1.8.1=classpath -org.ow2.asm:asm-analysis:9.6=classpath -org.ow2.asm:asm-commons:9.6=classpath -org.ow2.asm:asm-tree:9.6=classpath -org.ow2.asm:asm-util:9.6=classpath -org.ow2.asm:asm:9.6=classpath -org.slf4j:slf4j-api:1.7.30=classpath -org.tensorflow:tensorflow-lite-metadata:0.1.0-rc2=classpath -empty= diff --git a/dev/integration_tests/abstract_method_smoke_test/android/gradle.properties b/dev/integration_tests/abstract_method_smoke_test/android/gradle.properties deleted file mode 100644 index b7dcee2c391..00000000000 --- a/dev/integration_tests/abstract_method_smoke_test/android/gradle.properties +++ /dev/null @@ -1,3 +0,0 @@ -org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=2G -XX:+HeapDumpOnOutOfMemoryError -android.enableJetifier=true -android.useAndroidX=true diff --git a/dev/integration_tests/abstract_method_smoke_test/android/gradle/wrapper/gradle-wrapper.properties b/dev/integration_tests/abstract_method_smoke_test/android/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index afa1e8eb0a8..00000000000 --- a/dev/integration_tests/abstract_method_smoke_test/android/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip diff --git a/dev/integration_tests/abstract_method_smoke_test/android/project-app.lockfile b/dev/integration_tests/abstract_method_smoke_test/android/project-app.lockfile deleted file mode 100644 index c474395b359..00000000000 --- a/dev/integration_tests/abstract_method_smoke_test/android/project-app.lockfile +++ /dev/null @@ -1,218 +0,0 @@ -# This is a Gradle generated file for dependency locking. -# Manual edits can break the build and are not advised. -# This file is expected to be part of source control. -androidx.activity:activity:1.8.1=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.annotation:annotation-experimental:1.4.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.annotation:annotation-jvm:1.8.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.annotation:annotation:1.8.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.arch.core:core-common:2.2.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.arch.core:core-runtime:2.2.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.collection:collection:1.1.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.concurrent:concurrent-futures:1.1.0=debugRuntimeClasspath,debugUnitTestRuntimeClasspath,profileRuntimeClasspath,profileUnitTestRuntimeClasspath,releaseRuntimeClasspath,releaseUnitTestRuntimeClasspath -androidx.core:core-ktx:1.13.1=debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.core:core-ktx:1.2.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugImplementationDependenciesMetadata,profileApiDependenciesMetadata,profileImplementationDependenciesMetadata,releaseApiDependenciesMetadata,releaseImplementationDependenciesMetadata -androidx.core:core:1.13.1=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.customview:customview:1.0.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.fragment:fragment:1.7.1=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.interpolator:interpolator:1.0.0=debugRuntimeClasspath,debugUnitTestRuntimeClasspath,profileRuntimeClasspath,profileUnitTestRuntimeClasspath,releaseRuntimeClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-common-java8:2.7.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-common:2.7.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-livedata-core-ktx:2.7.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-livedata-core:2.7.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-livedata:2.7.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-process:2.7.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-runtime:2.7.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-viewmodel-savedstate:2.7.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-viewmodel:2.7.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.loader:loader:1.0.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.profileinstaller:profileinstaller:1.3.1=debugRuntimeClasspath,debugUnitTestRuntimeClasspath,profileRuntimeClasspath,profileUnitTestRuntimeClasspath,releaseRuntimeClasspath,releaseUnitTestRuntimeClasspath -androidx.savedstate:savedstate:1.2.1=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.startup:startup-runtime:1.1.1=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.tracing:tracing:1.2.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.versionedparcelable:versionedparcelable:1.1.1=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.viewpager:viewpager:1.0.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.window.extensions.core:core:1.0.0=debugRuntimeClasspath,debugUnitTestRuntimeClasspath,profileRuntimeClasspath,profileUnitTestRuntimeClasspath,releaseRuntimeClasspath,releaseUnitTestRuntimeClasspath -androidx.window:window-java:1.2.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.window:window:1.2.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -com.android.tools.analytics-library:protos:27.1.3=lintClassPath -com.android.tools.analytics-library:shared:27.1.3=lintClassPath -com.android.tools.analytics-library:tracker:27.1.3=lintClassPath -com.android.tools.build:aapt2-proto:4.1.0-alpha01-6193524=lintClassPath -com.android.tools.build:aapt2:4.1.3-6503028=_internal_aapt2_binary -com.android.tools.build:apksig:4.1.3=lintClassPath -com.android.tools.build:apkzlib:4.1.3=lintClassPath -com.android.tools.build:builder-model:4.1.3=lintClassPath -com.android.tools.build:builder-test-api:4.1.3=lintClassPath -com.android.tools.build:builder:4.1.3=lintClassPath -com.android.tools.build:gradle-api:4.1.3=lintClassPath -com.android.tools.build:manifest-merger:27.1.3=lintClassPath -com.android.tools.ddms:ddmlib:27.1.3=lintClassPath -com.android.tools.ddms:ddmlib:31.7.0=_internal-unified-test-platform-android-device-provider-ddmlib -com.android.tools.emulator:proto:31.7.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention -com.android.tools.external.com-intellij:intellij-core:27.1.3=lintClassPath -com.android.tools.external.com-intellij:kotlin-compiler:27.1.3=lintClassPath -com.android.tools.external.org-jetbrains:uast:27.1.3=lintClassPath -com.android.tools.layoutlib:layoutlib-api:27.1.3=lintClassPath -com.android.tools.lint:lint-api:27.1.3=lintClassPath -com.android.tools.lint:lint-checks:27.1.3=lintClassPath -com.android.tools.lint:lint-gradle-api:27.1.3=lintClassPath -com.android.tools.lint:lint-gradle:27.1.3=lintClassPath -com.android.tools.lint:lint-model:27.1.3=lintClassPath -com.android.tools.lint:lint:27.1.3=lintClassPath -com.android.tools.utp:android-device-provider-ddmlib-proto:31.7.0=_internal-unified-test-platform-android-device-provider-ddmlib -com.android.tools.utp:android-device-provider-ddmlib:31.7.0=_internal-unified-test-platform-android-device-provider-ddmlib -com.android.tools.utp:android-device-provider-gradle-proto:31.7.0=_internal-unified-test-platform-android-device-provider-gradle -com.android.tools.utp:android-device-provider-gradle:31.7.0=_internal-unified-test-platform-android-device-provider-gradle -com.android.tools.utp:android-device-provider-profile-proto:31.7.0=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle -com.android.tools.utp:android-device-provider-profile:31.7.0=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle -com.android.tools.utp:android-test-plugin-host-additional-test-output-proto:31.7.0=_internal-unified-test-platform-android-test-plugin-host-additional-test-output -com.android.tools.utp:android-test-plugin-host-additional-test-output:31.7.0=_internal-unified-test-platform-android-test-plugin-host-additional-test-output -com.android.tools.utp:android-test-plugin-host-apk-installer-proto:31.7.0=_internal-unified-test-platform-android-test-plugin-host-apk-installer -com.android.tools.utp:android-test-plugin-host-apk-installer:31.7.0=_internal-unified-test-platform-android-test-plugin-host-apk-installer -com.android.tools.utp:android-test-plugin-host-coverage-proto:31.7.0=_internal-unified-test-platform-android-test-plugin-host-coverage -com.android.tools.utp:android-test-plugin-host-coverage:31.7.0=_internal-unified-test-platform-android-test-plugin-host-coverage -com.android.tools.utp:android-test-plugin-host-device-info-proto:31.7.0=_internal-unified-test-platform-android-test-plugin-host-device-info -com.android.tools.utp:android-test-plugin-host-device-info:31.7.0=_internal-unified-test-platform-android-test-plugin-host-device-info -com.android.tools.utp:android-test-plugin-host-emulator-control-proto:31.7.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control -com.android.tools.utp:android-test-plugin-host-emulator-control:31.7.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control -com.android.tools.utp:android-test-plugin-host-logcat-proto:31.7.0=_internal-unified-test-platform-android-test-plugin-host-logcat -com.android.tools.utp:android-test-plugin-host-logcat:31.7.0=_internal-unified-test-platform-android-test-plugin-host-logcat -com.android.tools.utp:android-test-plugin-host-retention-proto:31.7.0=_internal-unified-test-platform-android-test-plugin-host-retention -com.android.tools.utp:android-test-plugin-host-retention:31.7.0=_internal-unified-test-platform-android-test-plugin-host-retention -com.android.tools.utp:android-test-plugin-result-listener-gradle-proto:31.7.0=_internal-unified-test-platform-android-test-plugin-result-listener-gradle -com.android.tools.utp:android-test-plugin-result-listener-gradle:31.7.0=_internal-unified-test-platform-android-test-plugin-result-listener-gradle -com.android.tools.utp:utp-common:31.7.0=_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention -com.android.tools:annotations:27.1.3=lintClassPath -com.android.tools:annotations:31.7.0=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -com.android.tools:common:27.1.3=lintClassPath -com.android.tools:common:31.7.0=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -com.android.tools:dvlib:27.1.3=lintClassPath -com.android.tools:repository:27.1.3=lintClassPath -com.android.tools:sdk-common:27.1.3=lintClassPath -com.android.tools:sdklib:27.1.3=lintClassPath -com.android:signflinger:4.1.3=lintClassPath -com.android:zipflinger:4.1.3=lintClassPath -com.getkeepsafe.relinker:relinker:1.4.5=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -com.google.android:annotations:4.1.1.4=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -com.google.api.grpc:proto-google-common-protos:2.17.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -com.google.code.findbugs:jsr305:3.0.2=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle,lintClassPath -com.google.code.gson:gson:2.10.1=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -com.google.code.gson:gson:2.8.5=lintClassPath -com.google.crypto.tink:tink:1.7.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control -com.google.errorprone:error_prone_annotations:2.18.0=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -com.google.errorprone:error_prone_annotations:2.3.2=lintClassPath -com.google.guava:failureaccess:1.0.1=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle,lintClassPath -com.google.guava:guava:28.1-jre=lintClassPath -com.google.guava:guava:32.0.1-jre=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -com.google.guava:listenablefuture:1.0=debugRuntimeClasspath,debugUnitTestRuntimeClasspath,profileRuntimeClasspath,profileUnitTestRuntimeClasspath,releaseRuntimeClasspath,releaseUnitTestRuntimeClasspath -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle,lintClassPath -com.google.j2objc:j2objc-annotations:1.3=lintClassPath -com.google.j2objc:j2objc-annotations:2.8=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -com.google.jimfs:jimfs:1.1=lintClassPath -com.google.protobuf:protobuf-java:3.10.0=lintClassPath -com.google.protobuf:protobuf-java:3.22.3=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -com.google.testing.platform:android-device-provider-local:0.0.9-alpha02=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -com.google.testing.platform:android-driver-instrumentation:0.0.9-alpha02=_internal-unified-test-platform-android-driver-instrumentation,_internal-unified-test-platform-android-test-plugin-host-emulator-control -com.google.testing.platform:android-test-plugin:0.0.9-alpha02=_internal-unified-test-platform-android-test-plugin -com.google.testing.platform:core-proto:0.0.9-alpha02=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -com.google.testing.platform:core:0.0.9-alpha02=_internal-unified-test-platform-core -com.google.testing.platform:launcher:0.0.9-alpha02=_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-launcher -com.googlecode.json-simple:json-simple:1.1=lintClassPath -com.squareup:javawriter:2.5.0=lintClassPath -com.sun.activation:javax.activation:1.2.0=lintClassPath -com.sun.istack:istack-commons-runtime:3.0.7=lintClassPath -com.sun.xml.fastinfoset:FastInfoset:1.2.15=lintClassPath -commons-codec:commons-codec:1.10=lintClassPath -commons-io:commons-io:2.13.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention -commons-logging:commons-logging:1.2=lintClassPath -io.grpc:grpc-api:1.57.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -io.grpc:grpc-context:1.57.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -io.grpc:grpc-core:1.57.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -io.grpc:grpc-netty:1.57.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -io.grpc:grpc-protobuf-lite:1.57.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -io.grpc:grpc-protobuf:1.57.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -io.grpc:grpc-stub:1.57.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -io.netty:netty-buffer:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -io.netty:netty-codec-http2:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -io.netty:netty-codec-http:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -io.netty:netty-codec-socks:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -io.netty:netty-codec:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -io.netty:netty-common:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -io.netty:netty-handler-proxy:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -io.netty:netty-handler:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -io.netty:netty-resolver:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -io.netty:netty-transport-native-unix-common:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -io.netty:netty-transport:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -io.perfmark:perfmark-api:0.26.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -it.unimi.dsi:fastutil:7.2.0=lintClassPath -javax.activation:javax.activation-api:1.2.0=lintClassPath -javax.annotation:javax.annotation-api:1.3.2=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -javax.inject:javax.inject:1=lintClassPath -javax.xml.bind:jaxb-api:2.3.1=lintClassPath -net.java.dev.jna:jna-platform:5.6.0=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -net.java.dev.jna:jna:5.6.0=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle,kotlinCompilerClasspath,kotlinKlibCommonizerClasspath -net.sf.jopt-simple:jopt-simple:4.9=lintClassPath -net.sf.kxml:kxml2:2.3.0=_internal-unified-test-platform-android-device-provider-ddmlib,lintClassPath -org.apache.commons:commons-compress:1.12=lintClassPath -org.apache.httpcomponents:httpclient:4.5.6=lintClassPath -org.apache.httpcomponents:httpcore:4.4.10=lintClassPath -org.apache.httpcomponents:httpmime:4.5.6=lintClassPath -org.bouncycastle:bcpkix-jdk15on:1.56=lintClassPath -org.bouncycastle:bcprov-jdk15on:1.56=lintClassPath -org.checkerframework:checker-qual:2.8.1=lintClassPath -org.checkerframework:checker-qual:3.33.0=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -org.codehaus.groovy:groovy-all:2.4.15=lintClassPath -org.codehaus.mojo:animal-sniffer-annotations:1.18=lintClassPath -org.codehaus.mojo:animal-sniffer-annotations:1.23=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -org.glassfish.jaxb:jaxb-runtime:2.3.1=lintClassPath -org.glassfish.jaxb:txw2:2.3.1=lintClassPath -org.jacoco:org.jacoco.agent:0.8.7=androidJacocoAnt -org.jacoco:org.jacoco.ant:0.8.7=androidJacocoAnt -org.jacoco:org.jacoco.core:0.8.7=androidJacocoAnt -org.jacoco:org.jacoco.report:0.8.7=androidJacocoAnt -org.jetbrains.intellij.deps:trove4j:1.0.20200330=kotlinCompilerClasspath,kotlinKlibCommonizerClasspath -org.jetbrains.kotlin:kotlin-compiler-embeddable:1.8.10=kotlinCompilerClasspath,kotlinKlibCommonizerClasspath -org.jetbrains.kotlin:kotlin-daemon-embeddable:1.8.10=kotlinCompilerClasspath,kotlinKlibCommonizerClasspath -org.jetbrains.kotlin:kotlin-klib-commonizer-embeddable:1.8.10=kotlinKlibCommonizerClasspath -org.jetbrains.kotlin:kotlin-reflect:1.3.72=lintClassPath -org.jetbrains.kotlin:kotlin-reflect:1.6.10=kotlinCompilerClasspath,kotlinKlibCommonizerClasspath -org.jetbrains.kotlin:kotlin-script-runtime:1.8.10=kotlinCompilerClasspath,kotlinKlibCommonizerClasspath -org.jetbrains.kotlin:kotlin-stdlib-common:1.3.72=lintClassPath -org.jetbrains.kotlin:kotlin-stdlib-common:1.7.10=implementationDependenciesMetadata -org.jetbrains.kotlin:kotlin-stdlib-common:1.8.10=kotlinCompilerClasspath,kotlinKlibCommonizerClasspath -org.jetbrains.kotlin:kotlin-stdlib-common:1.8.22=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jetbrains.kotlin:kotlin-stdlib-common:1.9.20=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.72=lintClassPath -org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.7.10=implementationDependenciesMetadata -org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.20=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.9.20=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.72=lintClassPath -org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.20=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.9.20=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -org.jetbrains.kotlin:kotlin-stdlib:1.3.72=lintClassPath -org.jetbrains.kotlin:kotlin-stdlib:1.7.10=implementationDependenciesMetadata -org.jetbrains.kotlin:kotlin-stdlib:1.8.10=kotlinCompilerClasspath,kotlinKlibCommonizerClasspath -org.jetbrains.kotlin:kotlin-stdlib:1.8.22=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jetbrains.kotlin:kotlin-stdlib:1.9.20=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -org.jetbrains.kotlinx:atomicfu:0.20.2=debugApiDependenciesMetadata,debugImplementationDependenciesMetadata,profileApiDependenciesMetadata,profileImplementationDependenciesMetadata,releaseApiDependenciesMetadata,releaseImplementationDependenciesMetadata -org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.1=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jetbrains.kotlinx:kotlinx-coroutines-bom:1.6.4=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -org.jetbrains.kotlinx:kotlinx-coroutines-bom:1.7.1=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.6.4=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.7.1=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle -org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.1=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jetbrains.trove4j:trove4j:20160824=lintClassPath -org.jetbrains:annotations:13.0=_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle,debugApiDependenciesMetadata,debugImplementationDependenciesMetadata,implementationDependenciesMetadata,kotlinCompilerClasspath,kotlinKlibCommonizerClasspath,lintClassPath,profileApiDependenciesMetadata,profileImplementationDependenciesMetadata,releaseApiDependenciesMetadata,releaseImplementationDependenciesMetadata -org.jetbrains:annotations:23.0.0=_internal-unified-test-platform-android-device-provider-ddmlib,debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jvnet.staxex:stax-ex:1.8=lintClassPath -org.ow2.asm:asm-analysis:7.0=lintClassPath -org.ow2.asm:asm-analysis:9.1=androidJacocoAnt -org.ow2.asm:asm-commons:7.0=lintClassPath -org.ow2.asm:asm-commons:9.1=androidJacocoAnt -org.ow2.asm:asm-tree:7.0=lintClassPath -org.ow2.asm:asm-tree:9.1=androidJacocoAnt -org.ow2.asm:asm-util:7.0=lintClassPath -org.ow2.asm:asm:7.0=lintClassPath -org.ow2.asm:asm:9.1=androidJacocoAnt -empty=androidApis,androidJdkImage,androidTestApiDependenciesMetadata,androidTestCompileOnlyDependenciesMetadata,androidTestDebugApiDependenciesMetadata,androidTestDebugCompileOnlyDependenciesMetadata,androidTestDebugImplementationDependenciesMetadata,androidTestDebugIntransitiveDependenciesMetadata,androidTestDebugRuntimeOnlyDependenciesMetadata,androidTestImplementationDependenciesMetadata,androidTestIntransitiveDependenciesMetadata,androidTestProfileApiDependenciesMetadata,androidTestProfileCompileOnlyDependenciesMetadata,androidTestProfileImplementationDependenciesMetadata,androidTestProfileIntransitiveDependenciesMetadata,androidTestProfileRuntimeOnlyDependenciesMetadata,androidTestReleaseApiDependenciesMetadata,androidTestReleaseCompileOnlyDependenciesMetadata,androidTestReleaseImplementationDependenciesMetadata,androidTestReleaseIntransitiveDependenciesMetadata,androidTestReleaseRuntimeOnlyDependenciesMetadata,androidTestRuntimeOnlyDependenciesMetadata,androidTestUtil,apiDependenciesMetadata,compile,compileOnlyDependenciesMetadata,coreLibraryDesugaring,debugAndroidTestAnnotationProcessorClasspath,debugAndroidTestApiDependenciesMetadata,debugAndroidTestCompileOnlyDependenciesMetadata,debugAndroidTestImplementationDependenciesMetadata,debugAndroidTestIntransitiveDependenciesMetadata,debugAndroidTestRuntimeClasspath,debugAndroidTestRuntimeOnlyDependenciesMetadata,debugAnnotationProcessorClasspath,debugCompile,debugCompileOnly,debugCompileOnlyDependenciesMetadata,debugIntransitiveDependenciesMetadata,debugReverseMetadataValues,debugRuntimeOnlyDependenciesMetadata,debugUnitTestAnnotationProcessorClasspath,debugUnitTestApiDependenciesMetadata,debugUnitTestCompileOnlyDependenciesMetadata,debugUnitTestImplementationDependenciesMetadata,debugUnitTestIntransitiveDependenciesMetadata,debugUnitTestRuntimeOnlyDependenciesMetadata,debugWearBundling,intransitiveDependenciesMetadata,kotlinCompilerPluginClasspath,kotlinCompilerPluginClasspathDebug,kotlinCompilerPluginClasspathDebugAndroidTest,kotlinCompilerPluginClasspathDebugUnitTest,kotlinCompilerPluginClasspathProfile,kotlinCompilerPluginClasspathProfileUnitTest,kotlinCompilerPluginClasspathRelease,kotlinCompilerPluginClasspathReleaseUnitTest,kotlinNativeCompilerPluginClasspath,lintChecks,lintPublish,profileAnnotationProcessorClasspath,profileCompile,profileCompileOnly,profileCompileOnlyDependenciesMetadata,profileIntransitiveDependenciesMetadata,profileReverseMetadataValues,profileRuntimeOnlyDependenciesMetadata,profileUnitTestAnnotationProcessorClasspath,profileUnitTestApiDependenciesMetadata,profileUnitTestCompileOnlyDependenciesMetadata,profileUnitTestImplementationDependenciesMetadata,profileUnitTestIntransitiveDependenciesMetadata,profileUnitTestRuntimeOnlyDependenciesMetadata,profileWearBundling,releaseAnnotationProcessorClasspath,releaseCompile,releaseCompileOnly,releaseCompileOnlyDependenciesMetadata,releaseIntransitiveDependenciesMetadata,releaseReverseMetadataValues,releaseRuntimeOnlyDependenciesMetadata,releaseUnitTestAnnotationProcessorClasspath,releaseUnitTestApiDependenciesMetadata,releaseUnitTestCompileOnlyDependenciesMetadata,releaseUnitTestImplementationDependenciesMetadata,releaseUnitTestIntransitiveDependenciesMetadata,releaseUnitTestRuntimeOnlyDependenciesMetadata,releaseWearBundling,runtimeOnlyDependenciesMetadata,testApiDependenciesMetadata,testCompile,testCompileOnlyDependenciesMetadata,testDebugApiDependenciesMetadata,testDebugCompileOnlyDependenciesMetadata,testDebugImplementationDependenciesMetadata,testDebugIntransitiveDependenciesMetadata,testDebugRuntimeOnlyDependenciesMetadata,testFixturesApiDependenciesMetadata,testFixturesCompileOnlyDependenciesMetadata,testFixturesDebugApiDependenciesMetadata,testFixturesDebugCompileOnlyDependenciesMetadata,testFixturesDebugImplementationDependenciesMetadata,testFixturesDebugIntransitiveDependenciesMetadata,testFixturesDebugRuntimeOnlyDependenciesMetadata,testFixturesImplementationDependenciesMetadata,testFixturesIntransitiveDependenciesMetadata,testFixturesProfileApiDependenciesMetadata,testFixturesProfileCompileOnlyDependenciesMetadata,testFixturesProfileImplementationDependenciesMetadata,testFixturesProfileIntransitiveDependenciesMetadata,testFixturesProfileRuntimeOnlyDependenciesMetadata,testFixturesReleaseApiDependenciesMetadata,testFixturesReleaseCompileOnlyDependenciesMetadata,testFixturesReleaseImplementationDependenciesMetadata,testFixturesReleaseIntransitiveDependenciesMetadata,testFixturesReleaseRuntimeOnlyDependenciesMetadata,testFixturesRuntimeOnlyDependenciesMetadata,testImplementationDependenciesMetadata,testIntransitiveDependenciesMetadata,testProfileApiDependenciesMetadata,testProfileCompileOnlyDependenciesMetadata,testProfileImplementationDependenciesMetadata,testProfileIntransitiveDependenciesMetadata,testProfileRuntimeOnlyDependenciesMetadata,testReleaseApiDependenciesMetadata,testReleaseCompileOnlyDependenciesMetadata,testReleaseImplementationDependenciesMetadata,testReleaseIntransitiveDependenciesMetadata,testReleaseRuntimeOnlyDependenciesMetadata,testRuntimeOnlyDependenciesMetadata diff --git a/dev/integration_tests/abstract_method_smoke_test/android/project-integration_test.lockfile b/dev/integration_tests/abstract_method_smoke_test/android/project-integration_test.lockfile deleted file mode 100644 index 1326b8773fd..00000000000 --- a/dev/integration_tests/abstract_method_smoke_test/android/project-integration_test.lockfile +++ /dev/null @@ -1,67 +0,0 @@ -# This is a Gradle generated file for dependency locking. -# Manual edits can break the build and are not advised. -# This file is expected to be part of source control. -androidx.activity:activity:1.0.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.annotation:annotation-experimental:1.1.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.annotation:annotation:1.2.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.arch.core:core-common:2.1.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.arch.core:core-runtime:2.0.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.collection:collection:1.1.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.core:core:1.6.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.customview:customview:1.0.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.fragment:fragment:1.1.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-common-java8:2.2.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-common:2.2.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-livedata-core:2.0.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-livedata:2.0.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-runtime:2.2.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-viewmodel:2.1.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.loader:loader:1.0.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.savedstate:savedstate:1.0.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.test.espresso:espresso-core:3.2.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.test.espresso:espresso-idling-resource:3.2.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.test:monitor:1.2.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.test:rules:1.2.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.test:runner:1.2.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.tracing:tracing:1.0.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.versionedparcelable:versionedparcelable:1.1.1=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.viewpager:viewpager:1.0.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.window:window-java:1.0.0-beta04=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.window:window:1.0.0-beta04=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -com.google.code.findbugs:jsr305:3.0.2=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -com.google.errorprone:error_prone_annotations:2.3.2=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -com.google.guava:failureaccess:1.0.1=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -com.google.guava:guava:28.1-android=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -com.google.j2objc:j2objc-annotations:1.3=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -com.squareup:javawriter:2.1.1=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -javax.inject:javax.inject:1=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -junit:junit:4.12=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -net.bytebuddy:byte-buddy-agent:1.12.22=debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -net.bytebuddy:byte-buddy:1.12.22=debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -net.sf.kxml:kxml2:2.3.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.checkerframework:checker-compat-qual:2.5.5=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.codehaus.mojo:animal-sniffer-annotations:1.18=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.hamcrest:hamcrest-core:1.3=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.hamcrest:hamcrest-integration:1.3=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.hamcrest:hamcrest-library:1.3=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jacoco:org.jacoco.agent:0.8.7=androidJacocoAnt -org.jacoco:org.jacoco.ant:0.8.7=androidJacocoAnt -org.jacoco:org.jacoco.core:0.8.7=androidJacocoAnt -org.jacoco:org.jacoco.report:0.8.7=androidJacocoAnt -org.jetbrains.kotlin:kotlin-stdlib-common:1.5.31=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.5.30=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.5.30=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jetbrains.kotlin:kotlin-stdlib:1.5.31=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.2=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jetbrains:annotations:13.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.mockito:mockito-core:5.0.0=debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.mockito:mockito-inline:5.0.0=debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.objenesis:objenesis:3.3=debugUnitTestRuntimeClasspath,profileUnitTestRuntimeClasspath,releaseUnitTestRuntimeClasspath -org.ow2.asm:asm-analysis:9.1=androidJacocoAnt -org.ow2.asm:asm-commons:9.1=androidJacocoAnt -org.ow2.asm:asm-tree:9.1=androidJacocoAnt -org.ow2.asm:asm:9.1=androidJacocoAnt -empty=androidApis,androidJdkImage,androidTestUtil,coreLibraryDesugaring,debugAndroidTestAnnotationProcessorClasspath,debugAnnotationProcessorClasspath,debugUnitTestAnnotationProcessorClasspath,lintChecks,lintPublish,profileAnnotationProcessorClasspath,profileUnitTestAnnotationProcessorClasspath,releaseAnnotationProcessorClasspath,releaseUnitTestAnnotationProcessorClasspath diff --git a/dev/integration_tests/abstract_method_smoke_test/android/settings.gradle b/dev/integration_tests/abstract_method_smoke_test/android/settings.gradle deleted file mode 100644 index 4a155b35ec3..00000000000 --- a/dev/integration_tests/abstract_method_smoke_test/android/settings.gradle +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2014 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. - -// This file is auto generated. -// To update all the settings.gradle files in the Flutter repo, -// See dev/tools/bin/generate_gradle_lockfiles.dart. - -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 - } - settings.ext.flutterSdkPath = flutterSdkPath() - - includeBuild("${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle") - - repositories { - google() - mavenCentral() - gradlePluginPortal() - } -} - -buildscript { - dependencyLocking { - lockFile = file("${rootProject.projectDir}/buildscript-gradle.lockfile") - lockAllConfigurations() - } -} - -plugins { - id "dev.flutter.flutter-plugin-loader" version "1.0.0" - id "com.android.application" version "8.7.0" apply false - id "org.jetbrains.kotlin.android" version "1.8.10" apply false -} - -include ":app" diff --git a/dev/integration_tests/abstract_method_smoke_test/lib/main.dart b/dev/integration_tests/abstract_method_smoke_test/lib/main.dart deleted file mode 100644 index ef26951039b..00000000000 --- a/dev/integration_tests/abstract_method_smoke_test/lib/main.dart +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2014 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; - -Future main() async { - WidgetsFlutterBinding.ensureInitialized(); - const MethodChannel channel = MethodChannel('com.example.abstract_method_smoke_test'); - await channel.invokeMethod('show_keyboard'); - runApp(const MyApp()); - print('Test succeeded'); -} - -class MyApp extends StatelessWidget { - const MyApp({super.key}); - - @override - Widget build(BuildContext context) { - return MaterialApp( - title: 'Flutter Demo', - theme: ThemeData( - primarySwatch: Colors.blue, - ), - home: const HomePage(), - ); - } -} - -class HomePage extends StatefulWidget { - const HomePage({super.key}); - - @override - State createState() => _HomePage(); -} - -class _HomePage extends State { - @override - void initState() { - super.initState(); - - // Trigger the second route. - // https://github.com/flutter/flutter/issues/40126 - WidgetsBinding.instance.addPostFrameCallback((_) async { - Navigator.of(context).push( - MaterialPageRoute(builder: (_) => const SecondPage())); - }); - } - - @override - Widget build(BuildContext context) { - return const Scaffold(); - } -} - -class SecondPage extends StatelessWidget { - const SecondPage({super.key}); - - @override - Widget build(BuildContext context) { - return const Scaffold( - body: Column( - children: [ - Expanded( - child: AndroidView(viewType: 'simple') - ), - ], - ), - ); - } -} diff --git a/dev/integration_tests/abstract_method_smoke_test/pubspec.yaml b/dev/integration_tests/abstract_method_smoke_test/pubspec.yaml deleted file mode 100644 index 5d75dd77ba1..00000000000 --- a/dev/integration_tests/abstract_method_smoke_test/pubspec.yaml +++ /dev/null @@ -1,22 +0,0 @@ -name: abstract_method_smoke_test -description: A new Flutter project. - -version: 1.0.0+1 - -environment: - sdk: '>=3.2.0-0 <4.0.0' - -dependencies: - flutter: - sdk: flutter - - characters: 1.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - collection: 1.19.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - material_color_utilities: 0.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - meta: 1.15.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - vector_math: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - -flutter: - uses-material-design: true - -# PUBSPEC CHECKSUM: 98c4 diff --git a/dev/integration_tests/android_semantics_testing/pubspec.yaml b/dev/integration_tests/android_semantics_testing/pubspec.yaml index 746fcba5d84..2c29119dce7 100644 --- a/dev/integration_tests/android_semantics_testing/pubspec.yaml +++ b/dev/integration_tests/android_semantics_testing/pubspec.yaml @@ -1,7 +1,7 @@ name: android_semantics_testing description: Integration testing library for Android semantics environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/android_verified_input/pubspec.yaml b/dev/integration_tests/android_verified_input/pubspec.yaml index 4ae2053b3ab..7747431dc86 100644 --- a/dev/integration_tests/android_verified_input/pubspec.yaml +++ b/dev/integration_tests/android_verified_input/pubspec.yaml @@ -3,7 +3,7 @@ description: "An integration test for verified MotionEvents." publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 # Dependencies specify other packages that your package needs in order to work. # To automatically upgrade your package dependencies to the latest versions diff --git a/dev/integration_tests/android_views/pubspec.yaml b/dev/integration_tests/android_views/pubspec.yaml index 814132bf99a..c025f4e3710 100644 --- a/dev/integration_tests/android_views/pubspec.yaml +++ b/dev/integration_tests/android_views/pubspec.yaml @@ -4,7 +4,7 @@ publish_to: none description: An integration test for embedded platform views version: 1.0.0+1 environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/channels/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/dev/integration_tests/channels/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 3d0fb007b17..7bdc6244337 100644 --- a/dev/integration_tests/channels/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/dev/integration_tests/channels/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -59,6 +59,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/dev/integration_tests/channels/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/dev/integration_tests/channels/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 631cefe6073..66d03ad16dc 100644 --- a/dev/integration_tests/channels/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/dev/integration_tests/channels/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -59,6 +59,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/dev/integration_tests/channels/pubspec.yaml b/dev/integration_tests/channels/pubspec.yaml index b860e3c3e4f..7ff4e272394 100644 --- a/dev/integration_tests/channels/pubspec.yaml +++ b/dev/integration_tests/channels/pubspec.yaml @@ -2,7 +2,7 @@ name: channels description: Integration test for platform channels. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/deferred_components_test/pubspec.yaml b/dev/integration_tests/deferred_components_test/pubspec.yaml index 46a8b569f12..30c4dfb3a85 100644 --- a/dev/integration_tests/deferred_components_test/pubspec.yaml +++ b/dev/integration_tests/deferred_components_test/pubspec.yaml @@ -3,7 +3,7 @@ description: Integration test application for basic deferred components function publish_to: 'none' version: 1.0.0+1 environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/external_textures/pubspec.yaml b/dev/integration_tests/external_textures/pubspec.yaml index da25e9d9e59..4da239c046d 100644 --- a/dev/integration_tests/external_textures/pubspec.yaml +++ b/dev/integration_tests/external_textures/pubspec.yaml @@ -2,7 +2,7 @@ name: external_textures description: A test of Flutter integrating external textures. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/flavors/pubspec.yaml b/dev/integration_tests/flavors/pubspec.yaml index 5b95feb7a4c..dd610431ad6 100644 --- a/dev/integration_tests/flavors/pubspec.yaml +++ b/dev/integration_tests/flavors/pubspec.yaml @@ -2,7 +2,7 @@ name: flavors description: Integration test for build flavors. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/flutter_gallery/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/dev/integration_tests/flutter_gallery/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index d6d3adc607b..3bfe377a60b 100644 --- a/dev/integration_tests/flutter_gallery/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/dev/integration_tests/flutter_gallery/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -48,6 +48,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/dev/integration_tests/flutter_gallery/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/dev/integration_tests/flutter_gallery/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 0af47c9a884..1023454c983 100644 --- a/dev/integration_tests/flutter_gallery/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/dev/integration_tests/flutter_gallery/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -58,6 +58,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/dev/integration_tests/flutter_gallery/pubspec.yaml b/dev/integration_tests/flutter_gallery/pubspec.yaml index e4992bc8c70..80de055d08d 100644 --- a/dev/integration_tests/flutter_gallery/pubspec.yaml +++ b/dev/integration_tests/flutter_gallery/pubspec.yaml @@ -1,7 +1,7 @@ name: flutter_gallery environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/gradle_deprecated_settings/pubspec.yaml b/dev/integration_tests/gradle_deprecated_settings/pubspec.yaml index 7641d42216d..d1ef877fc1f 100644 --- a/dev/integration_tests/gradle_deprecated_settings/pubspec.yaml +++ b/dev/integration_tests/gradle_deprecated_settings/pubspec.yaml @@ -2,7 +2,7 @@ name: gradle_deprecated_settings description: Integration test for the current settings.gradle. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/hybrid_android_views/pubspec.yaml b/dev/integration_tests/hybrid_android_views/pubspec.yaml index dbd28241cc8..f8ffdac017b 100644 --- a/dev/integration_tests/hybrid_android_views/pubspec.yaml +++ b/dev/integration_tests/hybrid_android_views/pubspec.yaml @@ -4,7 +4,7 @@ publish_to: none description: An integration test for hybrid composition on Android version: 1.0.0+1 environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/ios_add2app_life_cycle/flutterapp/pubspec.yaml b/dev/integration_tests/ios_add2app_life_cycle/flutterapp/pubspec.yaml index 93abda900e7..e49ee739af9 100644 --- a/dev/integration_tests/ios_add2app_life_cycle/flutterapp/pubspec.yaml +++ b/dev/integration_tests/ios_add2app_life_cycle/flutterapp/pubspec.yaml @@ -14,7 +14,7 @@ description: A new flutter module project. version: 1.0.0+1 environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/ios_app_with_extensions/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/dev/integration_tests/ios_app_with_extensions/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 5e31d3d342f..c53e2b314e9 100644 --- a/dev/integration_tests/ios_app_with_extensions/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/dev/integration_tests/ios_app_with_extensions/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -48,6 +48,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/dev/integration_tests/ios_app_with_extensions/pubspec.yaml b/dev/integration_tests/ios_app_with_extensions/pubspec.yaml index 20f97957426..82719af091f 100644 --- a/dev/integration_tests/ios_app_with_extensions/pubspec.yaml +++ b/dev/integration_tests/ios_app_with_extensions/pubspec.yaml @@ -13,7 +13,7 @@ name: ios_app_with_extensions version: 1.0.0+1 environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/ios_platform_view_tests/pubspec.yaml b/dev/integration_tests/ios_platform_view_tests/pubspec.yaml index faf2d92c617..88e8fa6add4 100644 --- a/dev/integration_tests/ios_platform_view_tests/pubspec.yaml +++ b/dev/integration_tests/ios_platform_view_tests/pubspec.yaml @@ -3,7 +3,7 @@ name: ios_platform_view_tests version: 1.0.0+1 environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/link_hook/pubspec.yaml b/dev/integration_tests/link_hook/pubspec.yaml index 866073d14b0..63024069d68 100644 --- a/dev/integration_tests/link_hook/pubspec.yaml +++ b/dev/integration_tests/link_hook/pubspec.yaml @@ -3,7 +3,7 @@ description: "A new Dart FFI package project." version: 0.0.1 environment: - sdk: '>=3.5.0-154.0.dev <4.0.0' + sdk: ^3.7.0-0 dependencies: logging: 1.3.0 diff --git a/dev/integration_tests/native_driver_test/pubspec.yaml b/dev/integration_tests/native_driver_test/pubspec.yaml index 4bc6722de9a..e520c2eea8f 100644 --- a/dev/integration_tests/native_driver_test/pubspec.yaml +++ b/dev/integration_tests/native_driver_test/pubspec.yaml @@ -2,7 +2,7 @@ name: native_driver_test publish_to: none environment: - sdk: ^3.6.0-216.0.dev + sdk: ^3.7.0-0 dependencies: native_driver: diff --git a/dev/integration_tests/new_gallery/pubspec.yaml b/dev/integration_tests/new_gallery/pubspec.yaml index 7f7c7a82419..1f5af65e731 100644 --- a/dev/integration_tests/new_gallery/pubspec.yaml +++ b/dev/integration_tests/new_gallery/pubspec.yaml @@ -5,7 +5,7 @@ version: 2.10.2+021002 # See README.md for details on versioning. environment: flutter: ^3.13.0 - sdk: ^3.1.0 + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/non_nullable/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/dev/integration_tests/non_nullable/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index e67b2808af0..4f746537f28 100644 --- a/dev/integration_tests/non_nullable/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/dev/integration_tests/non_nullable/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -50,6 +50,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/dev/integration_tests/non_nullable/pubspec.yaml b/dev/integration_tests/non_nullable/pubspec.yaml index a02172d379a..f345c620baf 100644 --- a/dev/integration_tests/non_nullable/pubspec.yaml +++ b/dev/integration_tests/non_nullable/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/platform_interaction/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/dev/integration_tests/platform_interaction/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index e67b2808af0..4f746537f28 100644 --- a/dev/integration_tests/platform_interaction/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/dev/integration_tests/platform_interaction/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -50,6 +50,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/dev/integration_tests/platform_interaction/pubspec.yaml b/dev/integration_tests/platform_interaction/pubspec.yaml index 9d6c43e9495..f6f4cb01665 100644 --- a/dev/integration_tests/platform_interaction/pubspec.yaml +++ b/dev/integration_tests/platform_interaction/pubspec.yaml @@ -2,7 +2,7 @@ name: platform_interaction description: Integration test for platform interactions. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/release_smoke_test/pubspec.yaml b/dev/integration_tests/release_smoke_test/pubspec.yaml index 05c1c9f2471..1bdda7f8580 100644 --- a/dev/integration_tests/release_smoke_test/pubspec.yaml +++ b/dev/integration_tests/release_smoke_test/pubspec.yaml @@ -1,7 +1,7 @@ name: release_smoke_test environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/spell_check/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/dev/integration_tests/spell_check/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 5e31d3d342f..c53e2b314e9 100644 --- a/dev/integration_tests/spell_check/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/dev/integration_tests/spell_check/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -48,6 +48,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/dev/integration_tests/spell_check/pubspec.yaml b/dev/integration_tests/spell_check/pubspec.yaml index bd73c9271f2..81d9efa5b15 100644 --- a/dev/integration_tests/spell_check/pubspec.yaml +++ b/dev/integration_tests/spell_check/pubspec.yaml @@ -18,7 +18,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 # Dependencies specify other packages that your package needs in order to work. # To automatically upgrade your package dependencies to the latest versions diff --git a/dev/integration_tests/ui/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/dev/integration_tests/ui/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index e67b2808af0..4f746537f28 100644 --- a/dev/integration_tests/ui/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/dev/integration_tests/ui/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -50,6 +50,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/dev/integration_tests/ui/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/dev/integration_tests/ui/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index d17300d4216..8b2b70c1aa4 100644 --- a/dev/integration_tests/ui/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/dev/integration_tests/ui/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -48,6 +48,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/dev/integration_tests/ui/pubspec.yaml b/dev/integration_tests/ui/pubspec.yaml index e0673f5eb29..d81acb29b08 100644 --- a/dev/integration_tests/ui/pubspec.yaml +++ b/dev/integration_tests/ui/pubspec.yaml @@ -2,7 +2,7 @@ name: integration_ui description: Flutter non-plugin UI integration tests. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/web/pubspec.yaml b/dev/integration_tests/web/pubspec.yaml index 5db21a37dd8..2331ea81930 100644 --- a/dev/integration_tests/web/pubspec.yaml +++ b/dev/integration_tests/web/pubspec.yaml @@ -2,7 +2,7 @@ name: web_integration description: Integration test for web compilation. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 flutter: assets: diff --git a/dev/integration_tests/web_compile_tests/pubspec.yaml b/dev/integration_tests/web_compile_tests/pubspec.yaml index 5684a688e01..28018e808ab 100644 --- a/dev/integration_tests/web_compile_tests/pubspec.yaml +++ b/dev/integration_tests/web_compile_tests/pubspec.yaml @@ -1,6 +1,6 @@ name: web_compile_tests environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/web_e2e_tests/pubspec.yaml b/dev/integration_tests/web_e2e_tests/pubspec.yaml index 40e58aec169..c1b03eb736d 100644 --- a/dev/integration_tests/web_e2e_tests/pubspec.yaml +++ b/dev/integration_tests/web_e2e_tests/pubspec.yaml @@ -2,7 +2,7 @@ name: web_e2e_tests publish_to: none environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 flutter: assets: diff --git a/dev/integration_tests/wide_gamut_test/pubspec.yaml b/dev/integration_tests/wide_gamut_test/pubspec.yaml index 7dd528f1760..b54cad0812d 100644 --- a/dev/integration_tests/wide_gamut_test/pubspec.yaml +++ b/dev/integration_tests/wide_gamut_test/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/integration_tests/windows_startup_test/pubspec.yaml b/dev/integration_tests/windows_startup_test/pubspec.yaml index d95b46839e5..07640d71e90 100644 --- a/dev/integration_tests/windows_startup_test/pubspec.yaml +++ b/dev/integration_tests/windows_startup_test/pubspec.yaml @@ -2,7 +2,7 @@ name: windows_startup_test description: Integration test for Windows app's startup. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/manual_tests/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/dev/manual_tests/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 5e31d3d342f..c53e2b314e9 100644 --- a/dev/manual_tests/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/dev/manual_tests/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -48,6 +48,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/dev/manual_tests/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/dev/manual_tests/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index db2b65d11bb..fe609a765cf 100644 --- a/dev/manual_tests/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/dev/manual_tests/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -48,6 +48,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/dev/manual_tests/pubspec.yaml b/dev/manual_tests/pubspec.yaml index f1b2194bd05..3467fdf6d55 100644 --- a/dev/manual_tests/pubspec.yaml +++ b/dev/manual_tests/pubspec.yaml @@ -1,7 +1,7 @@ name: manual_tests environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/missing_dependency_tests/pubspec.yaml b/dev/missing_dependency_tests/pubspec.yaml index 6499f49c5f8..68f3a0b5248 100644 --- a/dev/missing_dependency_tests/pubspec.yaml +++ b/dev/missing_dependency_tests/pubspec.yaml @@ -1,7 +1,7 @@ name: missing_dependency_tests environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/snippets/pubspec.yaml b/dev/snippets/pubspec.yaml index 36b9fc0e795..65adcad7065 100644 --- a/dev/snippets/pubspec.yaml +++ b/dev/snippets/pubspec.yaml @@ -2,7 +2,7 @@ name: snippets description: A package for parsing and manipulating code samples in Flutter repo dartdoc comments. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: analyzer: 6.11.0 diff --git a/dev/tools/bin/format.dart b/dev/tools/bin/format.dart new file mode 100644 index 00000000000..dc5a978a27d --- /dev/null +++ b/dev/tools/bin/format.dart @@ -0,0 +1,256 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:io'; + +import 'package:args/args.dart'; +import 'package:path/path.dart' as path; +import 'package:process_runner/process_runner.dart'; + +Future main(List arguments) async { + final ArgParser parser = ArgParser(); + parser.addFlag('help', help: 'Print help.', abbr: 'h'); + parser.addFlag('fix', + abbr: 'f', + help: 'Instead of just checking for formatting errors, fix them in place.'); + parser.addFlag('all-files', + abbr: 'a', + help: 'Instead of just checking for formatting errors in changed files, ' + 'check for them in all files.'); + + late final ArgResults options; + try { + options = parser.parse(arguments); + } on FormatException catch (e) { + stderr.writeln('ERROR: $e'); + _usage(parser, exitCode: 0); + } + + if (options['help'] as bool) { + _usage(parser, exitCode: 0); + } + + final File script = File.fromUri(Platform.script).absolute; + final Directory flutterRoot = script.parent.parent.parent.parent; + + final bool result = (await DartFormatChecker( + flutterRoot: flutterRoot, + allFiles: options['all-files'] as bool, + ).check(fix: options['fix'] as bool)) == 0; + + exit(result ? 0 : 1); +} + +void _usage(ArgParser parser, {int exitCode = 1}) { + stderr.writeln('format.dart [--help] [--fix] [--all-files]'); + stderr.writeln(parser.usage); + exit(exitCode); +} + +class DartFormatChecker { + DartFormatChecker({ + required this.flutterRoot, + required this.allFiles, + }) : processRunner = ProcessRunner( + defaultWorkingDirectory: flutterRoot, + ); + + final Directory flutterRoot; + final bool allFiles; + final ProcessRunner processRunner; + + Future check({required bool fix}) async { + final String baseGitRef = await _getDiffBaseRevision(); + final List filesToCheck = await _getFileList( + types: ['*.dart'], + allFiles: allFiles, + baseGitRef: baseGitRef, + ); + return _checkFormat( + filesToCheck: filesToCheck, + fix: fix, + ); + } + + Future _getDiffBaseRevision() async { + String upstream = 'upstream'; + final String upstreamUrl = await _runGit( + ['remote', 'get-url', upstream], + processRunner, + failOk: true, + ); + if (upstreamUrl.isEmpty) { + upstream = 'origin'; + } + await _runGit(['fetch', upstream, 'main'], processRunner); + String result = ''; + try { + // This is the preferred command to use, but developer checkouts often do + // not have a clear fork point, so we fall back to just the regular + // merge-base in that case. + result = await _runGit( + ['merge-base', '--fork-point', 'FETCH_HEAD', 'HEAD'], + processRunner, + ); + } on ProcessRunnerException { + result = await _runGit(['merge-base', 'FETCH_HEAD', 'HEAD'], processRunner); + } + return result.trim(); + } + + Future _runGit( + List args, + ProcessRunner processRunner, { + bool failOk = false, + }) async { + final ProcessRunnerResult result = await processRunner.runProcess( + ['git', ...args], + failOk: failOk, + ); + return result.stdout; + } + + Future> _getFileList({ + required List types, + required bool allFiles, + required String baseGitRef, + }) async { + String output; + if (allFiles) { + output = await _runGit([ + 'ls-files', + '--', + ...types, + ], processRunner); + } else { + output = await _runGit([ + 'diff', + '-U0', + '--no-color', + '--diff-filter=d', + '--name-only', + baseGitRef, + '--', + ...types, + ], processRunner); + } + return output.split('\n').where((String line) => line.isNotEmpty).toList(); + } + + Future _checkFormat({ + required List filesToCheck, + required bool fix, + }) async { + final List cmd = [ + path.join(flutterRoot.path, 'bin', 'dart'), + 'format', + '--set-exit-if-changed', + '--show=none', + if (!fix) '--output=show', + if (fix) '--output=write', + ]; + final List jobs = []; + for (final String file in filesToCheck) { + jobs.add(WorkerJob([...cmd, file])); + } + final ProcessPool dartFmt = ProcessPool( + processRunner: processRunner, + printReport: _namedReport('dart format'), + ); + + Iterable incorrect; + if (!fix) { + final Stream completedJobs = dartFmt.startWorkers(jobs); + final List diffJobs = []; + await for (final WorkerJob completedJob in completedJobs) { + if (completedJob.result.exitCode == 1) { + diffJobs.add( + WorkerJob( + [ + 'git', + 'diff', + '--no-index', + '--no-color', + '--ignore-cr-at-eol', + '--', + completedJob.command.last, + '-', + ], + stdinRaw: _codeUnitsAsStream(completedJob.result.stdoutRaw), + ), + ); + } + } + final ProcessPool diffPool = ProcessPool( + processRunner: processRunner, + printReport: _namedReport('diff'), + ); + final List completedDiffs = await diffPool.runToCompletion(diffJobs); + incorrect = completedDiffs.where((WorkerJob job) => job.result.exitCode != 0); + } else { + final List completedJobs = await dartFmt.runToCompletion(jobs); + incorrect = completedJobs.where((WorkerJob job) => job.result.exitCode == 1); + } + + _clearOutput(); + + if (incorrect.isNotEmpty) { + final bool plural = incorrect.length > 1; + if (fix) { + stdout.writeln('Fixing ${incorrect.length} dart file${plural ? 's' : ''}' + ' which ${plural ? 'were' : 'was'} formatted incorrectly.'); + } else { + stderr.writeln('Found ${incorrect.length} Dart file${plural ? 's' : ''}' + ' which ${plural ? 'were' : 'was'} formatted incorrectly.'); + final String fileList = incorrect.map( + (WorkerJob job) => job.command[job.command.length - 2] + ).join(' '); + stdout.writeln(); + stdout.writeln('To fix, run `dart format $fileList` or:'); + stdout.writeln(); + stdout.writeln('git apply <> _codeUnitsAsStream(List? input) async* { + if (input != null) { + yield input; + } +} diff --git a/dev/tools/format.bat b/dev/tools/format.bat new file mode 100644 index 00000000000..46ed331d7ab --- /dev/null +++ b/dev/tools/format.bat @@ -0,0 +1,22 @@ +@ECHO off +REM Copyright 2014 The Flutter Authors. All rights reserved. +REM Use of this source code is governed by a BSD-style license that can be +REM found in the LICENSE file. + +SETLOCAL ENABLEDELAYEDEXPANSION + +FOR %%i IN ("%~dp0..\..") DO SET FLUTTER_ROOT=%%~fi + +REM Test if Git is available on the Host +where /q git || ECHO Error: Unable to find git in your PATH. && EXIT /B 1 + +SET tools_dir=%FLUTTER_ROOT%\dev\tools + +SET dart=%FLUTTER_ROOT%\bin\dart.bat + +cd "%tools_dir%" + +REM Do not use the CALL command in the next line to execute Dart. CALL causes +REM Windows to re-read the line from disk after the CALL command has finished +REM regardless of the ampersand chain. +"%dart%" pub get > NUL && "%dart%" "%tools_dir%\bin\format.dart" %* & exit /B !ERRORLEVEL! diff --git a/dev/tools/format.sh b/dev/tools/format.sh new file mode 100755 index 00000000000..eb37f067d97 --- /dev/null +++ b/dev/tools/format.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# Copyright 2014 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. + +set -e + +# Needed because if it is set, cd may print the path it changed to. +unset CDPATH + +# On Mac OS, readlink -f doesn't work, so follow_links traverses the path one +# link at a time, and then cds into the link destination and find out where it +# ends up. +# +# The function is enclosed in a subshell to avoid changing the working directory +# of the caller. +function follow_links() ( + cd -P "$(dirname -- "$1")" + file="$PWD/$(basename -- "$1")" + while [[ -h "$file" ]]; do + cd -P "$(dirname -- "$file")" + file="$(readlink -- "$file")" + cd -P "$(dirname -- "$file")" + file="$PWD/$(basename -- "$file")" + done + echo "$file" +) + +SCRIPT_DIR=$(follow_links "$(dirname -- "${BASH_SOURCE[0]}")") +FLUTTER_DIR="$(cd "$SCRIPT_DIR/../.."; pwd -P)" +DART="${FLUTTER_DIR}/bin/dart" + +cd "$SCRIPT_DIR" +"$DART" pub get > /dev/null +"$DART" \ + bin/format.dart \ + "$@" diff --git a/dev/tools/gen_defaults/bin/gen_defaults.dart b/dev/tools/gen_defaults/bin/gen_defaults.dart index 78918ca431a..5431e708f59 100644 --- a/dev/tools/gen_defaults/bin/gen_defaults.dart +++ b/dev/tools/gen_defaults/bin/gen_defaults.dart @@ -47,6 +47,7 @@ import 'package:gen_defaults/radio_template.dart'; import 'package:gen_defaults/search_bar_template.dart'; import 'package:gen_defaults/search_view_template.dart'; import 'package:gen_defaults/segmented_button_template.dart'; +import 'package:gen_defaults/slider_template.dart'; import 'package:gen_defaults/snackbar_template.dart'; import 'package:gen_defaults/surface_tint.dart'; import 'package:gen_defaults/switch_template.dart'; @@ -142,8 +143,7 @@ Future main(List args) async { SearchViewTemplate('SearchView', '$materialLib/search_anchor.dart', tokens).updateFile(); SegmentedButtonTemplate('md.comp.outlined-segmented-button', 'SegmentedButton', '$materialLib/segmented_button.dart', tokens).updateFile(); SnackbarTemplate('md.comp.snackbar', 'Snackbar', '$materialLib/snack_bar.dart', tokens).updateFile(); - // TODO(QuncCccccc): uncomment `SliderTemplate` once `Slider` widget is updated to match the latest M3 specs. - // SliderTemplate('md.comp.slider', 'Slider', '$materialLib/slider.dart', tokens).updateFile(); + SliderTemplate('md.comp.slider', 'Slider', '$materialLib/slider.dart', tokens).updateFile(); SurfaceTintTemplate('SurfaceTint', '$materialLib/elevation_overlay.dart', tokens).updateFile(); SwitchTemplate('Switch', '$materialLib/switch.dart', tokens).updateFile(); TimePickerTemplate('TimePicker', '$materialLib/time_picker.dart', tokens).updateFile(); diff --git a/dev/tools/gen_defaults/generated/used_tokens.csv b/dev/tools/gen_defaults/generated/used_tokens.csv index c5ecfb6f58e..139edf98e8e 100644 --- a/dev/tools/gen_defaults/generated/used_tokens.csv +++ b/dev/tools/gen_defaults/generated/used_tokens.csv @@ -655,6 +655,33 @@ md.comp.sheet.bottom.docked.drag-handle.height, md.comp.sheet.bottom.docked.drag-handle.width, md.comp.sheet.bottom.docked.modal.container.elevation, md.comp.sheet.bottom.docked.standard.container.elevation, +md.comp.slider.active.handle.padding, +md.comp.slider.active.stop-indicator.container.color, +md.comp.slider.active.stop-indicator.container.opacity, +md.comp.slider.active.track.color, +md.comp.slider.active.track.height, +md.comp.slider.disabled.active.stop-indicator.container.color, +md.comp.slider.disabled.active.track.color, +md.comp.slider.disabled.active.track.opacity, +md.comp.slider.disabled.handle.color, +md.comp.slider.disabled.handle.opacity, +md.comp.slider.disabled.handle.width, +md.comp.slider.disabled.inactive.stop-indicator.container.color, +md.comp.slider.disabled.inactive.track.color, +md.comp.slider.disabled.inactive.track.opacity, +md.comp.slider.focus.handle.width, +md.comp.slider.handle.color, +md.comp.slider.handle.height, +md.comp.slider.handle.width, +md.comp.slider.hover.handle.width, +md.comp.slider.inactive.stop-indicator.container.color, +md.comp.slider.inactive.stop-indicator.container.opacity, +md.comp.slider.inactive.track.color, +md.comp.slider.pressed.handle.width, +md.comp.slider.stop-indicator.size, +md.comp.slider.value-indicator.container.color, +md.comp.slider.value-indicator.label.label-text.color, +md.comp.slider.value-indicator.label.label-text.text-style, md.comp.snackbar.action.focus.label-text.color, md.comp.snackbar.action.hover.label-text.color, md.comp.snackbar.action.label-text.color, diff --git a/dev/tools/gen_defaults/lib/progress_indicator_template.dart b/dev/tools/gen_defaults/lib/progress_indicator_template.dart index 82e1a8b13ba..8c04d76a198 100644 --- a/dev/tools/gen_defaults/lib/progress_indicator_template.dart +++ b/dev/tools/gen_defaults/lib/progress_indicator_template.dart @@ -12,16 +12,35 @@ class ProgressIndicatorTemplate extends TokenTemplate { @override String generate() => ''' class _Circular${blockName}DefaultsM3 extends ProgressIndicatorThemeData { - _Circular${blockName}DefaultsM3(this.context); + _Circular${blockName}DefaultsM3(this.context, { required this.indeterminate }); final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; + final bool indeterminate; @override Color get color => ${componentColor('md.comp.progress-indicator.active-indicator')}; @override - Color get circularTrackColor => ${componentColor('md.comp.progress-indicator.track')}; + Color? get circularTrackColor => indeterminate ? null : ${componentColor('md.comp.progress-indicator.track')}; + + @override + double get strokeWidth => ${getToken('md.comp.progress-indicator.track.thickness')}; + + @override + double? get strokeAlign => CircularProgressIndicator.strokeAlignInside; + + @override + BoxConstraints get constraints => const BoxConstraints( + minWidth: 40.0, + minHeight: 40.0, + ); + + @override + double? get trackGap => ${getToken('md.comp.progress-indicator.active-indicator-track-space')}; + + @override + EdgeInsetsGeometry? get circularTrackPadding => const EdgeInsets.all(4.0); } class _Linear${blockName}DefaultsM3 extends ProgressIndicatorThemeData { diff --git a/dev/tools/gen_defaults/lib/search_view_template.dart b/dev/tools/gen_defaults/lib/search_view_template.dart index 77406ffc28a..f1696a97502 100644 --- a/dev/tools/gen_defaults/lib/search_view_template.dart +++ b/dev/tools/gen_defaults/lib/search_view_template.dart @@ -50,6 +50,9 @@ class _${blockName}DefaultsM3 extends ${blockName}ThemeData { @override EdgeInsetsGeometry? get barPadding => const EdgeInsets.symmetric(horizontal: 8.0); + @override + bool get shrinkWrap => false; + @override Color? get dividerColor => ${componentColor('md.comp.search-view.divider')}; } diff --git a/dev/tools/gen_defaults/lib/slider_template.dart b/dev/tools/gen_defaults/lib/slider_template.dart index 8ced06757f2..ff9fb64fa08 100644 --- a/dev/tools/gen_defaults/lib/slider_template.dart +++ b/dev/tools/gen_defaults/lib/slider_template.dart @@ -27,7 +27,7 @@ class _${blockName}DefaultsM3 extends SliderThemeData { Color? get inactiveTrackColor => ${componentColor('$tokenGroup.inactive.track')}; @override - Color? get secondaryActiveTrackColor => _colors.primary.withOpacity(0.54); + Color? get secondaryActiveTrackColor => ${componentColor('$tokenGroup.active.track')}.withOpacity(0.54); @override Color? get disabledActiveTrackColor => ${componentColor('$tokenGroup.disabled.active.track')}; @@ -36,49 +36,85 @@ class _${blockName}DefaultsM3 extends SliderThemeData { Color? get disabledInactiveTrackColor => ${componentColor('$tokenGroup.disabled.inactive.track')}; @override - Color? get disabledSecondaryActiveTrackColor => _colors.onSurface.withOpacity(0.12); + Color? get disabledSecondaryActiveTrackColor => ${componentColor('$tokenGroup.disabled.active.track')}; @override - Color? get activeTickMarkColor => ${componentColor('$tokenGroup.with-tick-marks.active.container')}; + Color? get activeTickMarkColor => ${componentColor('$tokenGroup.active.stop-indicator.container')}; @override - Color? get inactiveTickMarkColor => ${componentColor('$tokenGroup.with-tick-marks.inactive.container')}; + Color? get inactiveTickMarkColor => ${componentColor('$tokenGroup.inactive.stop-indicator.container')}; @override - Color? get disabledActiveTickMarkColor => ${componentColor('$tokenGroup.with-tick-marks.disabled.container')}; + Color? get disabledActiveTickMarkColor => ${componentColor('$tokenGroup.disabled.active.stop-indicator.container')}; @override - Color? get disabledInactiveTickMarkColor => ${componentColor('$tokenGroup.with-tick-marks.disabled.container')}; + Color? get disabledInactiveTickMarkColor => ${componentColor('$tokenGroup.disabled.inactive.stop-indicator.container')}; @override Color? get thumbColor => ${componentColor('$tokenGroup.handle')}; @override - Color? get disabledThumbColor => Color.alphaBlend(${componentColor('$tokenGroup.disabled.handle')}, _colors.surface); + Color? get disabledThumbColor => ${componentColor('$tokenGroup.disabled.handle')}; @override Color? get overlayColor => MaterialStateColor.resolveWith((Set states) { if (states.contains(MaterialState.dragged)) { - return ${componentColor('$tokenGroup.pressed.state-layer')}; + return _colors.primary.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { - return ${componentColor('$tokenGroup.hover.state-layer')}; + return _colors.primary.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return ${componentColor('$tokenGroup.focus.state-layer')}; + return _colors.primary.withOpacity(0.1); } return Colors.transparent; }); @override - TextStyle? get valueIndicatorTextStyle => ${textStyle('$tokenGroup.label.label-text')}!.copyWith( - color: ${componentColor('$tokenGroup.label.label-text')}, + TextStyle? get valueIndicatorTextStyle => ${textStyle('$tokenGroup.value-indicator.label.label-text')}!.copyWith( + color: ${componentColor('$tokenGroup.value-indicator.label.label-text')}, ); @override - SliderComponentShape? get valueIndicatorShape => const DropSliderValueIndicatorShape(); + Color? get valueIndicatorColor => ${componentColor('$tokenGroup.value-indicator.container')}; + + @override + SliderComponentShape? get valueIndicatorShape => const RoundedRectSliderValueIndicatorShape(); + + @override + SliderComponentShape? get thumbShape => const HandleThumbShape(); + + @override + SliderTrackShape? get trackShape => const GappedSliderTrackShape(); + + @override + SliderComponentShape? get overlayShape => const RoundSliderOverlayShape(); + + @override + SliderTickMarkShape? get tickMarkShape => const RoundSliderTickMarkShape(tickMarkRadius: ${getToken("$tokenGroup.stop-indicator.size")} / 2); + + @override + MaterialStateProperty? get thumbSize { + return MaterialStateProperty.resolveWith((Set states) { + if (states.contains(MaterialState.disabled)) { + return const Size(${getToken("$tokenGroup.disabled.handle.width")}, ${getToken("$tokenGroup.handle.height")}); + } + if (states.contains(MaterialState.hovered)) { + return const Size(${getToken("$tokenGroup.hover.handle.width")}, ${getToken("$tokenGroup.handle.height")}); + } + if (states.contains(MaterialState.focused)) { + return const Size(${getToken("$tokenGroup.focus.handle.width")}, ${getToken("$tokenGroup.handle.height")}); + } + if (states.contains(MaterialState.pressed)) { + return const Size(${getToken("$tokenGroup.pressed.handle.width")}, ${getToken("$tokenGroup.handle.height")}); + } + return const Size(${getToken("$tokenGroup.handle.width")}, ${getToken("$tokenGroup.handle.height")}); + }); + } + + @override + double? get trackGap => ${getToken("$tokenGroup.active.handle.padding")}; } '''; - } diff --git a/dev/tools/gen_defaults/pubspec.yaml b/dev/tools/gen_defaults/pubspec.yaml index 06c1f142879..b36a76a1f78 100644 --- a/dev/tools/gen_defaults/pubspec.yaml +++ b/dev/tools/gen_defaults/pubspec.yaml @@ -3,7 +3,7 @@ description: A command line script to generate Material component defaults from version: 1.0.0 environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: args: 2.6.0 diff --git a/dev/tools/gen_keycodes/pubspec.yaml b/dev/tools/gen_keycodes/pubspec.yaml index 0c5dfe316ab..6676ce66e9f 100644 --- a/dev/tools/gen_keycodes/pubspec.yaml +++ b/dev/tools/gen_keycodes/pubspec.yaml @@ -2,7 +2,7 @@ name: gen_keycodes description: Generates keycode source files from various resources. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: args: 2.6.0 diff --git a/dev/tools/native_driver/lib/src/backend/android/adb.dart b/dev/tools/native_driver/lib/src/backend/android/adb.dart index 34740481ade..5989c2bf587 100644 --- a/dev/tools/native_driver/lib/src/backend/android/adb.dart +++ b/dev/tools/native_driver/lib/src/backend/android/adb.dart @@ -11,7 +11,7 @@ import 'package:process/process.dart'; /// A minimal wrapper around the `adb` command-line tool. @internal class Adb { - const Adb._(this._prefixArgs, this._proccess); + const Adb._(this._prefixArgs, this._process); /// Creates a new `adb` command runner that uses the `adb` command-line tool. /// @@ -41,7 +41,7 @@ class Adb { } Future _runString(List args) async { - final io.ProcessResult result = await _proccess.run( + final io.ProcessResult result = await _process.run( [ ..._prefixArgs, ...args, @@ -55,7 +55,7 @@ class Adb { } Future _runBinary(List args) async { - final io.ProcessResult result = await _proccess.run( + final io.ProcessResult result = await _process.run( [ ..._prefixArgs, ...args, @@ -70,7 +70,7 @@ class Adb { } final List _prefixArgs; - final ProcessManager _proccess; + final ProcessManager _process; /// Returns whether the device is currently connected. /// @@ -161,7 +161,7 @@ class Adb { } } - /// Disable confirnations for immersive mode. + /// Disable confirmations for immersive mode. Future disableImmersiveModeConfirmations() async { final AdbStringResult result = await _runString([ 'shell', diff --git a/dev/tools/native_driver/lib/src/backend/android/driver.dart b/dev/tools/native_driver/lib/src/backend/android/driver.dart index 263959fcca6..5d966008dc6 100644 --- a/dev/tools/native_driver/lib/src/backend/android/driver.dart +++ b/dev/tools/native_driver/lib/src/backend/android/driver.dart @@ -86,7 +86,7 @@ final class AndroidNativeDriver implements NativeDriver { @override Future screenshot() async { - // Indentical wait to what `FlutterDriver.screenshot` does. + // Identical wait to what `FlutterDriver.screenshot` does. await _waitFor2s(); return _AdbScreencap(await _adb.screencap(), _tmpDir); } diff --git a/dev/tools/native_driver/lib/src/common.dart b/dev/tools/native_driver/lib/src/common.dart index 3f3635c951d..5999462fbe9 100644 --- a/dev/tools/native_driver/lib/src/common.dart +++ b/dev/tools/native_driver/lib/src/common.dart @@ -62,7 +62,7 @@ final class NativeResult extends Result { Map toJson() => const {}; } -/// An object that descrbes searching for _native_ elements. +/// An object that describes searching for _native_ elements. sealed class NativeFinder { const NativeFinder(); diff --git a/dev/tools/native_driver/lib/src/goldens.dart b/dev/tools/native_driver/lib/src/goldens.dart index bd0e180757b..4b1a3c11447 100644 --- a/dev/tools/native_driver/lib/src/goldens.dart +++ b/dev/tools/native_driver/lib/src/goldens.dart @@ -136,7 +136,7 @@ final class NaiveLocalFileComparator extends GoldenFileComparator { // late NativeDriver nativeDriver; /// Asserts that a [NativeScreenshot], [Future], or -/// [List] matches the golden image file indentified by [key], with an +/// [List] matches the golden image file identified by [key], with an /// optional [version] number]. /// /// The [key] may be either a [Uri] or a [String] representation of a URL. @@ -151,7 +151,7 @@ final class NaiveLocalFileComparator extends GoldenFileComparator { /// ## Golden File Testing /// /// The term __golden file__ refers to a master image that is considered the -/// true renmdering of a given widget, state, application, or other visual +/// true rendering of a given widget, state, application, or other visual /// representation you have chosen to capture. /// /// The master golden image files are tested against can be created or updated diff --git a/dev/tools/native_driver/pubspec.yaml b/dev/tools/native_driver/pubspec.yaml index 6bf7ce25b63..56b29050e17 100644 --- a/dev/tools/native_driver/pubspec.yaml +++ b/dev/tools/native_driver/pubspec.yaml @@ -1,7 +1,7 @@ name: native_driver environment: - sdk: ^3.5.0 + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/tools/pubspec.yaml b/dev/tools/pubspec.yaml index 65f66d560ff..3afdde5a1de 100644 --- a/dev/tools/pubspec.yaml +++ b/dev/tools/pubspec.yaml @@ -2,7 +2,7 @@ name: dev_tools description: Various repository development tools for flutter. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: archive: 3.6.1 @@ -12,6 +12,7 @@ dependencies: meta: 1.15.0 path: 1.9.1 process: 5.0.3 + process_runner: 4.2.0 pub_semver: 2.1.4 yaml: 3.1.2 @@ -63,4 +64,4 @@ dev_dependencies: web_socket_channel: 3.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" webkit_inspection_protocol: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" -# PUBSPEC CHECKSUM: f620 +# PUBSPEC CHECKSUM: 2d6b diff --git a/dev/tools/test/format_test.dart b/dev/tools/test/format_test.dart new file mode 100644 index 00000000000..0ca7f5232e4 --- /dev/null +++ b/dev/tools/test/format_test.dart @@ -0,0 +1,94 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:io' as io; + +import 'package:path/path.dart' as path; +import 'package:test/test.dart'; + +class FileContentPair { + FileContentPair({required this.name, required this.original, required this.formatted}); + + final String name; + final String original; + final String formatted; +} + +final FileContentPair dartContentPair = FileContentPair( + name: 'format_test.dart', + original: 'enum \n\nfoo {\n entry1,\n entry2,\n}', + formatted: 'enum foo { entry1, entry2 }\n', +); + +class TestFileFixture { + TestFileFixture(this.filePairs, this.baseDir) { + for (final FileContentPair filePair in filePairs) { + final io.File file = io.File(path.join(baseDir.path, filePair.name)); + file.writeAsStringSync(filePair.original); + files.add(file); + } + } + + final List files = []; + final io.Directory baseDir; + final List filePairs; + + void gitAdd() { + final List args = ['add']; + for (final io.File file in files) { + args.add(file.path); + } + + io.Process.runSync('git', args); + } + + void gitRemove() { + final List args = ['rm', '-f']; + for (final io.File file in files) { + args.add(file.path); + } + io.Process.runSync('git', args); + } + + Iterable getFileContents() { + final List results = []; + for (int i = 0; i < files.length; i++) { + final io.File file = files[i]; + final FileContentPair filePair = filePairs[i]; + final String content = file.readAsStringSync().replaceAll('\r\n', '\n'); + results.add( + FileContentPair(name: filePair.name, original: content, formatted: filePair.formatted), + ); + } + return results; + } +} + +void main() { + final io.File script = io.File(path.current).absolute; + final io.Directory flutterRoot = script.parent.parent; + final String formatterPath = path.join( + flutterRoot.path, + 'dev', + 'tools', + 'format.${io.Platform.isWindows ? 'bat' : 'sh'}', + ); + + test('Can fix Dart formatting errors', () { + final TestFileFixture fixture = TestFileFixture([ + dartContentPair, + ], flutterRoot); + try { + fixture.gitAdd(); + io.Process.runSync(formatterPath, ['--fix'], workingDirectory: flutterRoot.path); + + final Iterable files = fixture.getFileContents(); + for (final FileContentPair pair in files) { + expect(pair.original, equals(pair.formatted)); + } + } finally { + fixture.gitRemove(); + } + }); +} diff --git a/dev/tools/vitool/pubspec.yaml b/dev/tools/vitool/pubspec.yaml index ef8e713509d..3f7c7568457 100644 --- a/dev/tools/vitool/pubspec.yaml +++ b/dev/tools/vitool/pubspec.yaml @@ -4,7 +4,7 @@ version: 0.0.1 homepage: https://flutter.dev environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/dev/tracing_tests/pubspec.yaml b/dev/tracing_tests/pubspec.yaml index aa8d7607b54..a5582b7d145 100644 --- a/dev/tracing_tests/pubspec.yaml +++ b/dev/tracing_tests/pubspec.yaml @@ -2,7 +2,7 @@ name: tracing_tests description: Various tests for tracing in flutter/flutter environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/docs/contributing/Style-guide-for-Flutter-repo.md b/docs/contributing/Style-guide-for-Flutter-repo.md index f1c24c6e0c9..37177ceae2f 100644 --- a/docs/contributing/Style-guide-for-Flutter-repo.md +++ b/docs/contributing/Style-guide-for-Flutter-repo.md @@ -1079,7 +1079,7 @@ However, where possible avoid global constants. Rather than `kDefaultButtonColor ### Avoid abbreviations -Unless the abbreviation is more recognizable than the expansion (e.g. XML, HTTP, JSON), expand abbrevations +Unless the abbreviation is more recognizable than the expansion (e.g. XML, HTTP, JSON), expand abbreviations when selecting a name for an identifier. In general, avoid one-character names unless one character is idiomatic (for example, prefer `index` over `i`, but prefer `x` over `horizontalPosition`). diff --git a/docs/contributing/testing/Fix-failing-checks.md b/docs/contributing/testing/Fix-failing-checks.md new file mode 100644 index 00000000000..f66f360ba4b --- /dev/null +++ b/docs/contributing/testing/Fix-failing-checks.md @@ -0,0 +1,138 @@ +![Some checks were not successful](https://github.com/user-attachments/assets/95fd56e9-4839-4944-b9ac-cc45404896a2) + +# How to fix a PR's failing checks + +
+ +### tree-status + +![Tree is currently broken.](https://github.com/user-attachments/assets/b611d540-c4cb-47dc-a27f-bef8709f24ce) + +Unlike other checks, **tree-status** isn't tied to the pull request: +instead, it shows whether checks are passing in the main branch.\ +Failures can happen for a variety of reasons and should be addressed +before anything else is merged in. + +**What to do:** Once [review requirements](../Tree-hygiene.md#getting-a-code-review) +are met and all other checks are passing, a reviewer will add the +[**`autosubmit`**](../../infra/Landing-Changes-With-Autosubmit.md) label, +and then a bot will merge the PR once **tree-status** succeeds. + +
+ +### Google testing + +![Google testing](https://github.com/user-attachments/assets/7d1f9a66-b84a-4223-b57d-77b44f205d1c) + +A Google testing failure could be a flake ([see below](#flaking)), or it +might be due to changes in the PR (See +[Understanding Google Testing](../../infra/Understanding-Google-Testing.md) +for more info). +Google employees can view the test output and give feedback accordingly. + +**What to do:** If 2 weeks have gone by and nobody's looked into it, +feel free to [reach out on Discord](../Chat.md). + +
+ +### ci.yaml validation + +![ci.yaml validation](https://github.com/user-attachments/assets/545a55f8-5bde-460f-92dd-9d87788f9fe8) + +In order for checks to run correctly, the [.ci.yaml](../../../.ci.yaml) +file needs to stay in sync with the base branch. + +**What to do:** This check failure can be fixed by applying the latest changes +from master.\ +(The [Tree hygiene](../Tree-hygiene.md#using-git) page recommends updating +via rebase, rather than a merge commit.) + +![Update with rebase](https://github.com/user-attachments/assets/8bacd87f-410a-4a9c-8ad0-075dd05f3eff) + +
+ +## A bug in the PR + +Oftentimes, a change inadvertently breaks expected behavior.\ +When this happens, usually the best way to find out what's wrong is to +[**view the test output**](#view-the-test-output). + +If a **customer_testing** check is unsuccessful, it's a signal that something in the +[Flutter customer test registry](https://github.com/flutter/tests/) has failed. +This includes [package tests](../../ecosystem/testing/Understanding-Packages-tests.md) +along with other tests from open-source Flutter projects.\ +If a pull request requires an update to those external tests, it qualifies as a +[**breaking change**](../Tree-hygiene.md#handling-breaking-changes); +please avoid those when possible. + +If **Linux Analyze** fails, it's likely that one or more changes in the PR +violated a [linter rule](https://dart.dev/lints/).\ +Consider reviewing the steps outlined in +[setting up the framework dev environment](../../Setting-up-the-Framework-development-environment.md) +so that most of these problems get caught in static analysis right away. + +> [!NOTE] +> All Dart code is run through static analysis: +> this includes markdown code snippets in doc comments! +> +> See [Hixie's Natural Log](https://ln.hixie.ch/?start=1660174115) for more details. + +
+ +### View the test output + +Click on **Details** for the failing test, and then click +**View more details on flutter-dashboard**. + +![view more details](https://github.com/user-attachments/assets/df667176-205f-42b2-8997-885c50ab238d) + +The full test output is linked at the bottom of the page. + +![LUCI overview page](https://github.com/user-attachments/assets/9603c6ad-90ec-47e1-96e8-9e3430f2c1b8) + +
+ +Often, there will be a message that resembles the one below: + +``` +══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════ +The following TestFailure was thrown running a test: +Expected: exactly one matching candidate + Actual: _TextWidgetFinder:(ConnectionState.waiting, null, null, null)": []> + Which: means none were found but one was expected + +When the exception was thrown, this was the stack: +#4 main.. (…/packages/flutter/test/widgets/async_test.dart:115:7) + +#5 testWidgets.. (package:flutter_test/src/widget_tester.dart:189:15) + +#6 TestWidgetsFlutterBinding._runTestBody (package:flutter_test/src/binding.dart:1032:5) + + +(elided one frame from package:stack_trace) + +This was caught by the test expectation on the following line: + file:///b/s/w/ir/x/w/flutter/packages/flutter/test/widgets/async_test.dart line 115 +The test description was: + gracefully handles transition from null future +════════════════════════════════════════════════════════════════════════════════════════════════════ +``` + +From there, it's just a matter of finding the failing test, +[running it locally](./Running-and-writing-tests.md), +and figuring out how to fix it! + +
+ +### Flaking + +A check might "flake", or randomly fail, for a variety of reasons. + +Sometimes a flake resolves itself after changes are pushed to re-trigger +the checks. Consider [performing a rebase](#ciyaml-validation) to include +the latest changes from the main branch. + +Flakes often happen due to **infra errors**. +For information on how to view and report infrastructure bugs, see the +[infra failure overview](../../infra/Understanding-a-LUCI-build-failure.md#overview-of-an-infra-failure-build). diff --git a/docs/ecosystem/testing/Plugin-Tests.md b/docs/ecosystem/testing/Plugin-Tests.md index ded095af1d1..f20ef36f767 100644 --- a/docs/ecosystem/testing/Plugin-Tests.md +++ b/docs/ecosystem/testing/Plugin-Tests.md @@ -195,7 +195,7 @@ See below for instructions on bringing up test scaffolding in a plugin (*does no 1. Use of OCMock in new tests, especially Swift tests, is discouraged in favor of protocol-based programming and dependency injection. However, if your XCTests require OCMock, open the Package Dependencies section of the project in Xcode, and add the following dependency to - the RunnnerTests target: + the RunnerTests target: ``` https://github.com/erikdoe/ocmock diff --git a/docs/infra/Understanding-a-LUCI-build-failure.md b/docs/infra/Understanding-a-LUCI-build-failure.md index 0257f90c221..a217094e382 100644 --- a/docs/infra/Understanding-a-LUCI-build-failure.md +++ b/docs/infra/Understanding-a-LUCI-build-failure.md @@ -51,3 +51,5 @@ Please refer to the above example of the infra failure. 4. Check if a flaky bug has been filed in [the flaky issues list](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3A%22c%3A+flake%22) 5. File a new bug if needed 6. If a rerun is needed, please refer to step 6 in the above infra failure session. + +See also: [How to fix a PR's failing checks](../contributing/testing/Fix-failing-checks.md) diff --git a/docs/infra/merge_queue.md b/docs/infra/merge_queue.md new file mode 100644 index 00000000000..eaf5bbca0ef --- /dev/null +++ b/docs/infra/merge_queue.md @@ -0,0 +1,56 @@ +## Github Merge Queue + +If you are not hacking on flutter/flutter, you can stop reading now. + +> [!IMPORTANT] +> **TL;DR** GitHub merge queue will be enabled in the `flutter/flutter` repo, which slightly changes the PR merge process, but you should not notice a change in your workflow. + +On Friday November 15th, 2024, GitHub merge queue feature will be enabled in the `flutter/flutter` repo. After this change, pull requests will first need to pass merge queue tests before landing on the target branch (e.g. `main` or `master`). At this time, no additional tests will run in the merge queue. A PR that passes presubmit checks will be allowed to land on the target branch immediately. + +--- + +### What should I expect? + +The only visible change will be the merge button. Currently, the button looks like this: + +![Squash and merge button](https://github.com/flutter/assets-for-api-docs/blob/main/assets/wiki/squash_merge.png) + +With the merge queue, the button will now look like this: + +![Merge when ready button](https://github.com/flutter/assets-for-api-docs/blob/main/assets/wiki/merge_ready.png) + + +Unlike "Squash and merge", the new button does not immediately land the PR on the target branch, but instead enqueues your PR for extra checks in the merge queue. If you do not do anything, eventually your PR will land. + +--- + +### Can I still use autosubmit? + +Yes! Feel free to continue using the `autosubmit` label as normal. The bots will run your PR through the merge queue and land it automatically. + +If you have an older PR from before this change, `autosubmit` may refuse to merge it. Resync your pull request to resolve this issue. + +--- + +### What's "Remove from queue"? Can I click it? + +While your PR is enqueued, Github will show the following button: + +![Remove from queue button](https://github.com/flutter/assets-for-api-docs/blob/main/assets/wiki/remove_queue.png) + +When you press this button, GitHub will remove your PR from the queue, and the PR will no longer be landed by any automated machinery. + +> [!WARNING] +> Please only use this button in case of emergency. Adding and removing your PR from the queue costs in CI resources. Any CI work being done for your PR and all PRs that follow yours will be stopped and restarted. + +--- + +### What if I have questions? + +If you have any questions or concerns, or If you suspect you are unable to land your PRs for reasons other than the familiar test failures and flakes, please contact any of: [@yjbanov](https://github.com/yjbanov), [@jtmcdole](https://github.com/jtmcdole), [@christopherfujino](https://github.com/christopherfujino), [@Piinks](https://github.com/piinks). + +### Why do we need the merge queue? + +The main reason for this change is that `flutter/engine` and `flutter/flutter` repos will be combined into one "monorepo". In order to preserve the current lightweight dev cycle for the framework code, we need to provide pre-built engine artifacts. This way you don't need to compile any C++ code, or install extra tooling (e.g. `depot_tools`), when hacking on the framework alone. The merge queue is what will be building those engine binaries. + +The second reason is we want to be able to catch bugs earlier. Currently a PR can land on the target branch if it passes presubmit tests. However, there's no guarantee that those same tests will pass after the PR is combined with other concurrent changes to the code. When the merge queue runs tests, it will run them against combined code changes, discovering bugs from merge conflicts immediately. This should reduce the number of reverts that have to be done on our `main` and `master` branches, keeping the tree green for longer periods of time. diff --git a/docs/platforms/android/Kotlin-android-studio-formatting.md b/docs/platforms/android/Kotlin-android-studio-formatting.md new file mode 100644 index 00000000000..c5a1117be07 --- /dev/null +++ b/docs/platforms/android/Kotlin-android-studio-formatting.md @@ -0,0 +1,27 @@ +# Setting up Kotlin formatting in Android Studio + +Kotlin code in this repository is formatted and linted with [`ktlint`](https://github.com/pinterest/ktlint). +If you +1. have submitted Kotlin code only to learn this when the analyzer check fails +2. use Android Studio + + +then there is good news! Android Studio can be configured to use `ktlint` to automatically apply formatting and highlight issues. To do this: + + +1. Install the `ktlint` extension for Android Studio + + a. On Mac, this is `Android Studio > Settings > Plugins > ` Search for `ktlint`. + +2. Set the ruleset to be the same as the version used in [`.ci.yaml`](../../../.ci.yaml) (as of writing this is 1.1.1), and the baseline to be `dev/bots/test/analyze-test-input/ktlint-baseline.xml`. + + a. Both of these options should be available under `Android Studio > Settings > Tools > ktlint`. + +3. Additionally, Kotlin code in the Flutter repository currently uses some additional rules for compatibility with older versions of Kotlin. +These rules can only be configured by an `.editorconfig` file in the directory from which Android Studio was opened. To configure these rules, create a new `.editorconfig` file in the root of your flutter repository with the following content +``` +[*.{kt,kts}] +# Disable trailing commas to allow compatibility with Kotlin versions less than 1.4. +ij_kotlin_allow_trailing_comma = false +ij_kotlin_allow_trailing_comma_on_call_site = false +``` diff --git a/docs/releases/Quality-Assurance.md b/docs/releases/Quality-Assurance.md index f3f589325a6..dbea482a802 100644 --- a/docs/releases/Quality-Assurance.md +++ b/docs/releases/Quality-Assurance.md @@ -12,7 +12,7 @@ When a beta build is announced, switch to the beta channel: If you get a `git` error, then you probably have a contributor checkout of Flutter. Use git instead: -> `git fetch upstream/beta && git checkout beta` +> `git fetch upstream && git checkout upstream/beta` Either way, check that everything is as you expect: diff --git a/docs/triage/Flutter-Web-Triage.md b/docs/triage/Flutter-Web-Triage.md index 830bcacf5a9..7e0cfea8e0a 100644 --- a/docs/triage/Flutter-Web-Triage.md +++ b/docs/triage/Flutter-Web-Triage.md @@ -1,17 +1,16 @@ When triaging web issues follow the following process: -- Make sure there are no [unassigned P0 and P1 issues](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP1%2CP0+no%3Aassignee). -- Make sure there are no [P1 issues outside the backlog](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP1%2CP0+-project%3Aflutter%2F41+). -- Make sure there are no [P3 issues in the backlog](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+project%3Aflutter%2F41+label%3AP3). -- Make sure there are no assigned P2 and P3 issues (if you'd like to become a regular Flutter Web contributor, please ping yjbanov on Discord to be added to this list, and we'll watch that your issues are properly triaged): - - [ditman](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP2%2CP3+assignee%3Aditman) - - [eyebrowsoffire](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP2%2CP3+assignee%3Aeyebrowsoffire) - - [harryterkelsen](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP2%2CP3+assignee%3Aharryterkelsen) - - [tugorez](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP2%2CP3+assignee%3Atugorez) - - [kevmoo](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP2%2CP3+assignee%3Akevmoo) - - [mdebbar](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP2%2CP3+assignee%3Amdebbar) - - [yjbanov](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP2%2CP3+assignee%3Ayjbanov) -- All [P0 issues](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP0) are assigned and being worked on. -- The list of [P1 issues](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP1) should be manageable (<30 issues) -- The [list of open PRs](https://github.com/pulls?q=is%3Aopen+is%3Apr+archived%3Afalse+user%3Aflutter+sort%3Aupdated-asc+label%3Aplatform-web) should be manageable (<15). -- Triage [untriaged issues](https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3Ateam-web%2Cfyi-web+-label%3Atriaged-web+no%3Aassignee+-label%3A%22will+need+additional+triage%22+sort%3Aupdated-asc+-label%3A%22waiting+for+customer+response%22+) +* Make sure there are no [unassigned P0 and P1 issues](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP1%2CP0+no%3Aassignee). +* Make sure there are no [P1 issues outside the backlog](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP1%2CP0+-project%3Aflutter%2F41+). +* Make sure there are no [P3 issues in the backlog](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+project%3Aflutter%2F41+label%3AP3). +* Make sure there are no assigned P2 and P3 issues (if you'd like to become a regular Flutter Web contributor, please ping yjbanov on Discord to be added to this list, and we'll watch that your issues are properly triaged): + * [ditman](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP2%2CP3+assignee%3Aditman) + * [eyebrowsoffire](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP2%2CP3+assignee%3Aeyebrowsoffire) + * [harryterkelsen](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP2%2CP3+assignee%3Aharryterkelsen) + * [kevmoo](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP2%2CP3+assignee%3Akevmoo) + * [mdebbar](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP2%2CP3+assignee%3Amdebbar) + * [yjbanov](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP2%2CP3+assignee%3Ayjbanov) +* All [P0 issues](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP0) are assigned and being worked on. +* The list of [P1 issues](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Ateam-web+label%3AP1) should be manageable (<30 issues) +* The [list of open PRs](https://github.com/pulls?q=is%3Aopen+is%3Apr+archived%3Afalse+user%3Aflutter+sort%3Aupdated-asc+label%3Aplatform-web) should be manageable (<15). +* Triage [untriaged issues](https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3Ateam-web%2Cfyi-web+-label%3Atriaged-web+no%3Aassignee+-label%3A%22will+need+additional+triage%22+sort%3Aupdated-asc+-label%3A%22waiting+for+customer+response%22+) diff --git a/docs/triage/README.md b/docs/triage/README.md index 9068274328f..bff97547d0f 100644 --- a/docs/triage/README.md +++ b/docs/triage/README.md @@ -85,6 +85,7 @@ In general the flow chart for team assignment is as follows, stopping as soon as - If it's about the Flutter tool, add `team-tool`. - If it's about a first-party package: - If it's about `go_router` or `go_router_builder`, add `team-go_router`. + - If it's about `flutter_svg` or `vector_graphics`, add `team-engine`. - Otherwise, add `team-ecosystem`. - If none of the above apply, add `will need additional triage`. @@ -216,7 +217,7 @@ For more guidance on reviewing PRs, see [Tree Hygiene](../contributing/Tree-hygi ### Design Languages team (`team-design`) -- [Incoming issue list](https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3Ateam-design%2Cfyi-design+-label%3Atriaged-design+no%3Aassignee+-label%3A%22will+need+additional+triage%22+sort%3Aupdated-asc+-label%3A%22waiting+for+customer+response%22+) +- [Incoming issue list](https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3Ateam-design%2Cfyi-design+-label%3Atriaged-design+-label%3A%22will+need+additional+triage%22+sort%3Aupdated-asc+-label%3A%22waiting+for+customer+response%22+) - [P0 list](https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3Ateam-design+label%3AP0+sort%3Aupdated-asc) - [Design Languages PRs](https://github.com/flutter/flutter/pulls?q=is%3Aopen+is%3Apr+label%3A%22f%3A+material+design%22%2C%22f%3A+cupertino%22+sort%3Aupdated-asc+draft%3Afalse) @@ -245,7 +246,7 @@ In addition, consider these issues that fall under another team's triage, but ar - [P0 list](https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3Ateam-framework+label%3AP0+sort%3Aupdated-asc) - [PR list](https://github.com/flutter/flutter/pulls?q=is%3Aopen+is%3Apr+label%3Aframework+-label%3A%22f%3A+material+design%22+-label%3A%22f%3A+cupertino%22+sort%3Acreated-desc+draft%3Afalse) -- [Incoming issue list](https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3Ateam-framework%2Cfyi-framework+-label%3Atriaged-framework+no%3Aassignee+-label%3A%22will+need+additional+triage%22+sort%3Aupdated-asc+-label%3A%22waiting+for+customer+response%22+) +- [Incoming issue list](https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3Ateam-framework%2Cfyi-framework+-label%3Atriaged-framework+-label%3A%22will+need+additional+triage%22+sort%3Aupdated-asc+-label%3A%22waiting+for+customer+response%22+) ### Games team (`team-games`) diff --git a/examples/api/lib/material/color_scheme/dynamic_content_color.0.dart b/examples/api/lib/material/color_scheme/dynamic_content_color.0.dart index 2dde166abaf..d88896a7467 100644 --- a/examples/api/lib/material/color_scheme/dynamic_content_color.0.dart +++ b/examples/api/lib/material/color_scheme/dynamic_content_color.0.dart @@ -9,26 +9,34 @@ import 'package:flutter/material.dart'; const Widget divider = SizedBox(height: 10); const double narrowScreenWidthThreshold = 400; -void main() => runApp(DynamicColorExample()); +void main() => runApp(const DynamicColorExample()); class DynamicColorExample extends StatefulWidget { - DynamicColorExample({super.key}); + const DynamicColorExample({ + this.loadColorScheme, + super.key, + }); - final List images = [ - const NetworkImage( + static const List images = [ + NetworkImage( 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_1.png'), - const NetworkImage( + NetworkImage( 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_2.png'), - const NetworkImage( + NetworkImage( 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_3.png'), - const NetworkImage( + NetworkImage( 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_4.png'), - const NetworkImage( + NetworkImage( 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_5.png'), - const NetworkImage( + NetworkImage( 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_6.png'), ]; + final Future Function( + ImageProvider provider, + Brightness brightness, + )? loadColorScheme; + @override State createState() => _DynamicColorExampleState(); } @@ -48,7 +56,7 @@ class _DynamicColorExampleState extends State { isLoading = true; currentColorScheme = const ColorScheme.light(); WidgetsBinding.instance.addPostFrameCallback((_) { - _updateImage(widget.images[selectedImage]); + _updateImage(DynamicColorExample.images[selectedImage]); isLoading = false; }); } @@ -105,7 +113,7 @@ class _DynamicColorExampleState extends State { onChanged: (bool value) { setState(() { isLight = value; - _updateImage(widget.images[selectedImage]); + _updateImage(DynamicColorExample.images[selectedImage]); }); }) ], @@ -120,7 +128,7 @@ class _DynamicColorExampleState extends State { divider, _imagesRow( context, - widget.images, + DynamicColorExample.images, colorScheme, ), divider, @@ -186,13 +194,23 @@ class _DynamicColorExampleState extends State { } Future _updateImage(ImageProvider provider) async { - final ColorScheme newColorScheme = await ColorScheme.fromImageProvider( - provider: provider, brightness: isLight ? Brightness.light : Brightness.dark); + final ColorScheme newColorScheme; + if (widget.loadColorScheme != null) { + newColorScheme = await widget.loadColorScheme!( + provider, + isLight ? Brightness.light : Brightness.dark, + ); + } else { + newColorScheme = await ColorScheme.fromImageProvider( + provider: provider, + brightness: isLight ? Brightness.light : Brightness.dark, + ); + } if (!mounted) { return; } setState(() { - selectedImage = widget.images.indexOf(provider); + selectedImage = DynamicColorExample.images.indexOf(provider); currentColorScheme = newColorScheme; }); } @@ -227,7 +245,7 @@ class _DynamicColorExampleState extends State { child: GestureDetector( onTap: () => _updateImage(image), child: Card( - color: widget.images.indexOf(image) == selectedImage + color: DynamicColorExample.images.indexOf(image) == selectedImage ? colorScheme.primaryContainer : colorScheme.surface, child: Padding( diff --git a/examples/api/lib/material/navigation_bar/navigation_bar.1.dart b/examples/api/lib/material/navigation_bar/navigation_bar.1.dart index edd5e2d0946..ec823c4aae8 100644 --- a/examples/api/lib/material/navigation_bar/navigation_bar.1.dart +++ b/examples/api/lib/material/navigation_bar/navigation_bar.1.dart @@ -63,6 +63,8 @@ class _NavigationExampleState extends State { const SizedBox(height: 10), OverflowBar( spacing: 10.0, + overflowAlignment: OverflowBarAlignment.center, + overflowSpacing: 10.0, children: [ ElevatedButton( onPressed: () { diff --git a/examples/api/lib/material/page_transitions_theme/page_transitions_theme.0.dart b/examples/api/lib/material/page_transitions_theme/page_transitions_theme.0.dart index e541cd898de..dc2dab2eed7 100644 --- a/examples/api/lib/material/page_transitions_theme/page_transitions_theme.0.dart +++ b/examples/api/lib/material/page_transitions_theme/page_transitions_theme.0.dart @@ -15,7 +15,6 @@ class PageTransitionsThemeApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( - useMaterial3: true, // Defines the page transition animations used by MaterialPageRoute // for different target platforms. // Non-specified target platforms will default to diff --git a/examples/api/lib/material/page_transitions_theme/page_transitions_theme.3.dart b/examples/api/lib/material/page_transitions_theme/page_transitions_theme.3.dart new file mode 100644 index 00000000000..42cb9376530 --- /dev/null +++ b/examples/api/lib/material/page_transitions_theme/page_transitions_theme.3.dart @@ -0,0 +1,149 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/material.dart'; + +/// Flutter code sample for the default Android U page transition theme +/// [FadeForwardsPageTransitionsBuilder]. Tapping each list tile navigates to +/// a second page, which slides in from right to left while fading in. +/// Simultaneously, the first page slides out in the same direction while +/// fading out. + +void main() => runApp(const PageTransitionsThemeApp()); + +class PageTransitionsThemeApp extends StatelessWidget { + const PageTransitionsThemeApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + debugShowCheckedModeBanner: false, + theme: ThemeData( + pageTransitionsTheme: PageTransitionsTheme( + builders: Map.fromIterable( + TargetPlatform.values, value: (_) => const FadeForwardsPageTransitionsBuilder() + ), + ), + ), + home: const HomePage(), + ); + } +} + +class HomePage extends StatelessWidget { + const HomePage({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + leading: IconButton(icon: const Icon(Icons.dehaze), onPressed: () {}), + actions: [ + IconButton(icon: const Icon(Icons.search), onPressed: () {}), + IconButton(icon: const Icon(Icons.more_vert), onPressed: () {}), + ], + ), + body: Column( + children: [ + Text('Messages', style: Theme.of(context).textTheme.headlineLarge), + Expanded( + child: Padding( + padding: const EdgeInsets.all(20.0), + child: Card( + clipBehavior: Clip.antiAlias, + elevation: 0, + color: Theme.of(context).colorScheme.surfaceContainerLowest, + child: ListView( + children: List.generate(Colors.primaries.length, (int index) { + final Text kittenName = Text('Kitten $index'); + final CircleAvatar avatar = CircleAvatar(backgroundColor: Colors.primaries[index]); + final String message = index.isEven + ? 'Hello hooman! My name is Kitten $index' + : "What's up hooman! My name is Kitten $index"; + return ListTile( + leading: avatar, + title: kittenName, + subtitle: Text(message), + trailing: Text('$index seconds ago'), + onTap: () { + Navigator.of(context).push( + MaterialPageRoute( + builder: (BuildContext context) + => SecondPage( + kittenName: kittenName, + avatar: avatar, + message: message, + ), + ), + ); + }, + ); + }), + ), + ), + ), + ), + ], + ) + ); + } +} + +class SecondPage extends StatelessWidget { + const SecondPage({ + super.key, + required this.kittenName, + required this.avatar, + required this.message, + }); + final Text kittenName; + final CircleAvatar avatar; + final String message; + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + leading: const BackButton(), + title: kittenName, + centerTitle: false, + actions: [ + IconButton(icon: const Icon(Icons.search), onPressed: () {}), + IconButton(icon: const Icon(Icons.more_vert), onPressed: () {}), + ], + ), + body: Padding( + padding: const EdgeInsets.all(20.0), + child: IntrinsicHeight( + child: Row( + children: [ + avatar, + ConstrainedBox( + constraints: const BoxConstraints(minHeight: 50), + child: Card( + elevation: 0.0, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.only( + topLeft: Radius.circular(20), + topRight: Radius.circular(20), + bottomLeft: Radius.circular(5), + bottomRight: Radius.circular(20), + ) + ), + color: Theme.of(context).colorScheme.surfaceContainerLowest, + child: Center( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 15.0), + child: Text(message) + ), + ), + ), + ) + ], + ), + ), + ), + ); + } +} diff --git a/examples/api/lib/material/progress_indicator/circular_progress_indicator.0.dart b/examples/api/lib/material/progress_indicator/circular_progress_indicator.0.dart index a41036a8c45..af695cea4b1 100644 --- a/examples/api/lib/material/progress_indicator/circular_progress_indicator.0.dart +++ b/examples/api/lib/material/progress_indicator/circular_progress_indicator.0.dart @@ -6,10 +6,10 @@ import 'package:flutter/material.dart'; /// Flutter code sample for [CircularProgressIndicator]. -void main() => runApp(const ProgressIndicatorApp()); +void main() => runApp(const ProgressIndicatorExampleApp()); -class ProgressIndicatorApp extends StatelessWidget { - const ProgressIndicatorApp({super.key}); +class ProgressIndicatorExampleApp extends StatelessWidget { + const ProgressIndicatorExampleApp({super.key}); @override Widget build(BuildContext context) { @@ -28,19 +28,18 @@ class ProgressIndicatorExample extends StatefulWidget { class _ProgressIndicatorExampleState extends State with TickerProviderStateMixin { late AnimationController controller; + bool year2023 = true; @override void initState() { + super.initState(); controller = AnimationController( - /// [AnimationController]s can be created with `vsync: this` because of - /// [TickerProviderStateMixin]. vsync: this, duration: const Duration(seconds: 5), )..addListener(() { - setState(() {}); - }); - controller.repeat(reverse: true); - super.initState(); + setState(() {}); + }) + ..repeat(reverse: true); } @override @@ -52,18 +51,32 @@ class _ProgressIndicatorExampleState extends State wit @override Widget build(BuildContext context) { return Scaffold( - body: Padding( - padding: const EdgeInsets.all(20.0), + body: Center( child: Column( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, + spacing: 16.0, + mainAxisAlignment: MainAxisAlignment.center, children: [ - Text( - 'Circular progress indicator with a fixed color', - style: Theme.of(context).textTheme.titleLarge, + const Text('Determinate CircularProgressIndicator'), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: CircularProgressIndicator( + year2023: year2023, + value: controller.value, + ), ), - CircularProgressIndicator( - value: controller.value, - semanticsLabel: 'Circular progress indicator', + const Text('Indeterminate CircularProgressIndicator'), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: CircularProgressIndicator(year2023: year2023), + ), + SwitchListTile( + value: year2023, + title: year2023 ? const Text('Switch to latest M3 style') : const Text('Switch to year2023 M3 style'), + onChanged: (bool value) { + setState(() { + year2023 = !year2023; + }); + }, ), ], ), diff --git a/examples/api/lib/material/progress_indicator/circular_progress_indicator.1.dart b/examples/api/lib/material/progress_indicator/circular_progress_indicator.1.dart index 6b228f89e20..2398b6747d6 100644 --- a/examples/api/lib/material/progress_indicator/circular_progress_indicator.1.dart +++ b/examples/api/lib/material/progress_indicator/circular_progress_indicator.1.dart @@ -6,10 +6,10 @@ import 'package:flutter/material.dart'; /// Flutter code sample for [CircularProgressIndicator]. -void main() => runApp(const ProgressIndicatorApp()); +void main() => runApp(const ProgressIndicatorExampleApp()); -class ProgressIndicatorApp extends StatelessWidget { - const ProgressIndicatorApp({super.key}); +class ProgressIndicatorExampleApp extends StatelessWidget { + const ProgressIndicatorExampleApp({super.key}); @override Widget build(BuildContext context) { @@ -57,18 +57,17 @@ class _ProgressIndicatorExampleState extends State wit body: Padding( padding: const EdgeInsets.all(20.0), child: Column( + spacing: 16.0, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Circular progress indicator', style: Theme.of(context).textTheme.titleLarge, ), - const SizedBox(height: 30), CircularProgressIndicator( value: controller.value, semanticsLabel: 'Circular progress indicator', ), - const SizedBox(height: 10), Row( children: [ Expanded( diff --git a/examples/api/lib/material/progress_indicator/linear_progress_indicator.0.dart b/examples/api/lib/material/progress_indicator/linear_progress_indicator.0.dart index 2d7a626d83c..2c04e1e8a90 100644 --- a/examples/api/lib/material/progress_indicator/linear_progress_indicator.0.dart +++ b/examples/api/lib/material/progress_indicator/linear_progress_indicator.0.dart @@ -27,9 +27,9 @@ class ProgressIndicatorExample extends StatefulWidget { _ProgressIndicatorExampleState(); } -class _ProgressIndicatorExampleState extends State - with TickerProviderStateMixin { +class _ProgressIndicatorExampleState extends State with TickerProviderStateMixin { late AnimationController controller; + bool year2023 = true; @override void initState() { @@ -54,18 +54,33 @@ class _ProgressIndicatorExampleState extends State @override Widget build(BuildContext context) { return Scaffold( - body: Padding( - padding: const EdgeInsets.all(20.0), - child: Column( - spacing: 16.0, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Text('Determinate LinearProgressIndicator'), - LinearProgressIndicator(value: controller.value), - const Text('Indeterminate LinearProgressIndicator'), - const LinearProgressIndicator(), - ], - ), + body: Column( + spacing: 16.0, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Text('Determinate LinearProgressIndicator'), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: LinearProgressIndicator( + year2023: year2023, + value: controller.value, + ), + ), + const Text('Indeterminate LinearProgressIndicator'), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: LinearProgressIndicator(year2023: year2023), + ), + SwitchListTile( + value: year2023, + title: year2023 ? const Text('Switch to latest M3 style') : const Text('Switch to year2023 M3 style'), + onChanged: (bool value) { + setState(() { + year2023 = !year2023; + }); + }, + ), + ], ), ); } diff --git a/examples/api/lib/material/progress_indicator/linear_progress_indicator.1.dart b/examples/api/lib/material/progress_indicator/linear_progress_indicator.1.dart index 6663c60b43e..f8422c4c7ba 100644 --- a/examples/api/lib/material/progress_indicator/linear_progress_indicator.1.dart +++ b/examples/api/lib/material/progress_indicator/linear_progress_indicator.1.dart @@ -58,18 +58,17 @@ class _ProgressIndicatorExampleState extends State body: Padding( padding: const EdgeInsets.all(20.0), child: Column( + spacing: 16.0, mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( 'Linear progress indicator', style: TextStyle(fontSize: 20), ), - const SizedBox(height: 30), LinearProgressIndicator( value: determinate ? controller.value : null, semanticsLabel: 'Linear progress indicator', ), - const SizedBox(height: 10), Row( children: [ Expanded( diff --git a/examples/api/lib/material/selectable_region/selectable_region.0.dart b/examples/api/lib/material/selectable_region/selectable_region.0.dart index 72925863a13..7ab61b14617 100644 --- a/examples/api/lib/material/selectable_region/selectable_region.0.dart +++ b/examples/api/lib/material/selectable_region/selectable_region.0.dart @@ -15,7 +15,8 @@ class SelectableRegionExampleApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( - home: SelectionArea( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, child: Scaffold( appBar: AppBar(title: const Text('SelectableRegion Sample')), body: const Center( @@ -93,7 +94,7 @@ class _RenderSelectableAdapter extends RenderProxyBox with Selectable, Selection final ValueNotifier _geometry; Color get selectionColor => _selectionColor; - late Color _selectionColor; + Color _selectionColor; set selectionColor(Color value) { if (_selectionColor == value) { return; @@ -271,6 +272,20 @@ class _RenderSelectableAdapter extends RenderProxyBox with Selectable, Selection return value.hasSelection ? const SelectedContent(plainText: 'Custom Text') : null; } + @override + SelectedContentRange? getSelection() { + if (!value.hasSelection) { + return null; + } + return const SelectedContentRange( + startOffset: 0, + endOffset: 1, + ); + } + + @override + int get contentLength => 1; + LayerLink? _startHandle; LayerLink? _endHandle; diff --git a/examples/api/lib/material/selection_area/selection_area.1.dart b/examples/api/lib/material/selection_area/selection_area.1.dart new file mode 100644 index 00000000000..c4c40ee5b35 --- /dev/null +++ b/examples/api/lib/material/selection_area/selection_area.1.dart @@ -0,0 +1,136 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +/// Flutter code sample for [SelectionArea]. + +void main() => runApp(const SelectionAreaSelectionListenerExampleApp()); + +class SelectionAreaSelectionListenerExampleApp extends StatelessWidget { + const SelectionAreaSelectionListenerExampleApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'Flutter Demo', + theme: ThemeData( + colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), + useMaterial3: true, + ), + home: const MyHomePage(title: 'Flutter Demo Home Page'), + ); + } +} + +class MyHomePage extends StatefulWidget { + const MyHomePage({super.key, required this.title}); + + final String title; + + @override + State createState() => _MyHomePageState(); +} + +class _MyHomePageState extends State { + final SelectionListenerNotifier _selectionNotifier = SelectionListenerNotifier(); + SelectableRegionSelectionStatus? _selectableRegionStatus; + + void _handleOnSelectionStateChanged(SelectableRegionSelectionStatus status) { + setState(() { + _selectableRegionStatus = status; + }); + } + + @override + void dispose() { + _selectionNotifier.dispose(); + _selectableRegionStatus = null; + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: Theme.of(context).colorScheme.inversePrimary, + title: Text(widget.title), + ), + body: Center( + child: Column( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final (int? offset, String label) in <(int? offset, String label)>[ + (_selectionNotifier.registered ? _selectionNotifier.selection.range?.startOffset : null, 'StartOffset'), + (_selectionNotifier.registered ? _selectionNotifier.selection.range?.endOffset : null, 'EndOffset'), + ]) + Text('Selection $label: $offset'), + Text('Selection Status: ${_selectionNotifier.registered ? _selectionNotifier.selection.status : 'SelectionListenerNotifier not registered.'}'), + Text('Selectable Region Status: $_selectableRegionStatus'), + ], + ), + const SizedBox(height: 15.0,), + SelectionArea( + child: MySelectableText( + selectionNotifier: _selectionNotifier, + onChanged: _handleOnSelectionStateChanged, + ), + ), + ], + ), + ), + ); + } +} + +class MySelectableText extends StatefulWidget { + const MySelectableText({ + super.key, + required this.selectionNotifier, + required this.onChanged, + }); + + final SelectionListenerNotifier selectionNotifier; + final ValueChanged onChanged; + + @override + State createState() => _MySelectableTextState(); +} + +class _MySelectableTextState extends State { + ValueListenable? _selectableRegionScope; + + void _handleOnSelectableRegionChanged() { + if (_selectableRegionScope == null) { + return; + } + widget.onChanged.call(_selectableRegionScope!.value); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _selectableRegionScope?.removeListener(_handleOnSelectableRegionChanged); + _selectableRegionScope = SelectableRegionSelectionStatusScope.maybeOf(context); + _selectableRegionScope?.addListener(_handleOnSelectableRegionChanged); + } + + @override + void dispose() { + _selectableRegionScope?.removeListener(_handleOnSelectableRegionChanged); + _selectableRegionScope = null; + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return SelectionListener( + selectionNotifier: widget.selectionNotifier, + child: const Text('This is some text under a SelectionArea that can be selected.'), + ); + } +} diff --git a/examples/api/lib/material/selection_area/selection_area.2.dart b/examples/api/lib/material/selection_area/selection_area.2.dart new file mode 100644 index 00000000000..a4b7dfe4c0c --- /dev/null +++ b/examples/api/lib/material/selection_area/selection_area.2.dart @@ -0,0 +1,407 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:math'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +/// Flutter code sample for [SelectionArea]. + +void main() => runApp(const SelectionAreaColorTextRedExampleApp()); + +class SelectionAreaColorTextRedExampleApp extends StatelessWidget { + const SelectionAreaColorTextRedExampleApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'Flutter Demo', + theme: ThemeData( + colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), + useMaterial3: true, + ), + home: const MyHomePage(title: 'Flutter Demo Home Page'), + ); + } +} + +class MyHomePage extends StatefulWidget { + const MyHomePage({super.key, required this.title}); + + final String title; + + @override + State createState() => _MyHomePageState(); +} + +typedef LocalSpanRange = ({int startOffset, int endOffset}); + +class _MyHomePageState extends State { + final SelectionListenerNotifier _selectionNotifier = SelectionListenerNotifier(); + final ContextMenuController _menuController = ContextMenuController(); + final GlobalKey selectionAreaKey = GlobalKey(); + + // The data of the top level TextSpans. Each TextSpan is mapped to a LocalSpanRange, + // which is the range the textspan covers relative to the SelectionListener it is under. + Map dataSourceMap = {}; + // The data of the bulleted list contained within a WidgetSpan. Each bullet is mapped + // to a LocalSpanRange, being the range the bullet covers relative to the SelectionListener + // it is under. + Map bulletSourceMap = {}; + Map> widgetSpanMaps = >{}; + // The origin data used to restore the demo to its initial state. + late final Map originSourceData; + late final Map originBulletSourceData; + + void _initData() { + const String bulletListTitle = 'This is some bulleted list:\n'; + final List bullets = [ + for (int i = 1; i <= 7; i += 1) + '• Bullet $i' + ]; + final TextSpan bulletedList = TextSpan( + text: bulletListTitle, + children: [ + WidgetSpan( + child: Column( + children: [ + for (final String bullet in bullets) + Padding( + padding: const EdgeInsets.only(left: 20.0), + child: Text(bullet), + ) + ], + ), + ), + ], + ); + + int currentOffset = 0; + // Map bulleted list span to a local range using its concrete length calculated + // from the length of its title and each individual bullet. + dataSourceMap[(startOffset: currentOffset, endOffset: bulletListTitle.length + bullets.join().length)] = bulletedList; + currentOffset += bulletListTitle.length; + widgetSpanMaps[currentOffset] = bulletSourceMap; + // Map individual bullets to a local range. + for (final String bullet in bullets) { + bulletSourceMap[(startOffset: currentOffset, endOffset: currentOffset + bullet.length)] = TextSpan(text: bullet); + currentOffset += bullet.length; + } + + const TextSpan secondTextParagraph = TextSpan( + text: 'This is some text in a text widget.', + children: [TextSpan(text: ' This is some more text in the same text widget.')], + ); + const TextSpan thirdTextParagraph = TextSpan(text: 'This is some text in another text widget.'); + // Map second and third paragraphs to local ranges. + dataSourceMap[(startOffset: currentOffset, endOffset: currentOffset + secondTextParagraph.toPlainText(includeSemanticsLabels: false).length)] = secondTextParagraph; + currentOffset += secondTextParagraph.toPlainText(includeSemanticsLabels: false).length; + dataSourceMap[(startOffset: currentOffset, endOffset: currentOffset + thirdTextParagraph.toPlainText(includeSemanticsLabels: false).length)] = thirdTextParagraph; + + // Save the origin data so we can revert our changes. + originSourceData = {}; + for (final MapEntry entry in dataSourceMap.entries) { + originSourceData[entry.key] = entry.value; + } + originBulletSourceData = {}; + for (final MapEntry entry in bulletSourceMap.entries) { + originBulletSourceData[entry.key] = entry.value; + } + } + + void _handleSelectableRegionStatusChanged(SelectableRegionSelectionStatus status) { + if (_menuController.isShown) { + ContextMenuController.removeAny(); + } + if (_selectionNotifier.selection.status != SelectionStatus.uncollapsed + || status != SelectableRegionSelectionStatus.finalized) { + return; + } + if (selectionAreaKey.currentState == null + || !selectionAreaKey.currentState!.mounted + || selectionAreaKey.currentState!.selectableRegion.contextMenuAnchors.secondaryAnchor == null) { + return; + } + final SelectedContentRange? selectedContentRange = _selectionNotifier.selection.range; + if (selectedContentRange == null) { + return; + } + _menuController.show( + context: context, + contextMenuBuilder: (BuildContext context) { + return TapRegion( + onTapOutside: (PointerDownEvent event) { + if (_menuController.isShown) { + ContextMenuController.removeAny(); + } + }, + child: AdaptiveTextSelectionToolbar.buttonItems( + buttonItems: [ + ContextMenuButtonItem( + onPressed: () { + ContextMenuController.removeAny(); + _colorSelectionRed( + selectedContentRange, + dataMap: dataSourceMap, + coloringChildSpan: false, + ); + selectionAreaKey.currentState!.selectableRegion.clearSelection(); + }, + label: 'Color Text Red', + ), + ], + anchors: TextSelectionToolbarAnchors(primaryAnchor: selectionAreaKey.currentState!.selectableRegion.contextMenuAnchors.secondaryAnchor!), + ), + ); + }, + ); + } + + void _colorSelectionRed( + SelectedContentRange selectedContentRange, { + required Map dataMap, + required bool coloringChildSpan, + }) { + for (final MapEntry entry in dataMap.entries) { + final LocalSpanRange entryLocalRange = entry.key; + final int normalizedStartOffset = min(selectedContentRange.startOffset, selectedContentRange.endOffset); + final int normalizedEndOffset = max(selectedContentRange.startOffset, selectedContentRange.endOffset); + if (normalizedStartOffset > entryLocalRange.endOffset) { + continue; + } + if (normalizedEndOffset < entryLocalRange.startOffset) { + continue; + } + // The selection details is covering the current entry so let's color the range red. + final TextSpan rawSpan = entry.value; + // Determine local ranges relative to rawSpan. + final int clampedLocalStart = normalizedStartOffset < entryLocalRange.startOffset ? entryLocalRange.startOffset : normalizedStartOffset; + final int clampedLocalEnd = normalizedEndOffset > entryLocalRange.endOffset ? entryLocalRange.endOffset : normalizedEndOffset; + final int startOffset = (clampedLocalStart - entryLocalRange.startOffset).abs(); + final int endOffset = startOffset + (clampedLocalEnd - clampedLocalStart).abs(); + final List beforeSelection = []; + final List insideSelection = []; + final List afterSelection = []; + int count = 0; + rawSpan.visitChildren((InlineSpan child) { + if (child is TextSpan) { + final String? rawText = child.text; + if (rawText != null) { + if (count < startOffset) { + final int newStart = min(startOffset - count, rawText.length); + final int globalNewStart = count + newStart; + // Collect spans before selection. + beforeSelection.add( + TextSpan( + style: child.style, + text: rawText.substring(0, newStart), + ), + ); + // Check if this span also contains the selection. + if (globalNewStart == startOffset && newStart < rawText.length) { + final int newStartAfterSelection = min(newStart + (endOffset - startOffset), rawText.length); + final int globalNewStartAfterSelection = count + newStartAfterSelection; + insideSelection.add( + TextSpan( + style: const TextStyle(color: Colors.red).merge(entry.value.style), + text: rawText.substring(newStart, newStartAfterSelection), + ), + ); + // Check if this span contains content after the selection. + if (globalNewStartAfterSelection == endOffset && newStartAfterSelection < rawText.length) { + afterSelection.add( + TextSpan( + style: child.style, + text: rawText.substring(newStartAfterSelection), + ), + ); + } + } + } else if (count >= endOffset) { + // Collect spans after selection. + afterSelection.add(TextSpan(style: child.style, text: rawText)); + } else { + // Collect spans inside selection. + final int newStart = min(endOffset - count, rawText.length); + final int globalNewStart = count + newStart; + insideSelection.add(TextSpan(style: const TextStyle(color: Colors.red), text: rawText.substring(0, newStart))); + // Check if this span contains content after the selection. + if (globalNewStart == endOffset && newStart < rawText.length) { + afterSelection.add(TextSpan(style: child.style, text: rawText.substring(newStart))); + } + } + count += rawText.length; + } + } else if (child is WidgetSpan) { + if (!widgetSpanMaps.containsKey(count)) { + // We have arrived at a WidgetSpan but it is unaccounted for. + return true; + } + final Map widgetSpanSourceMap = widgetSpanMaps[count]!; + if (count < startOffset && count + (widgetSpanSourceMap.keys.last.endOffset - widgetSpanSourceMap.keys.first.startOffset).abs() < startOffset) { + // When the count is less than the startOffset and we are at a widgetspan + // it is still possible that the startOffset is somewhere within the widgetspan, + // so we should try to color the selection red for the widgetspan. + // + // If the calculated widgetspan length would not extend the count past the + // startOffset then add this widgetspan to the beforeSelection, and + // continue walking the tree. + beforeSelection.add(child); + count += (widgetSpanSourceMap.keys.last.endOffset - widgetSpanSourceMap.keys.first.startOffset).abs(); + return true; + } else if (count >= endOffset) { + afterSelection.add(child); + count += (widgetSpanSourceMap.keys.last.endOffset - widgetSpanSourceMap.keys.first.startOffset).abs(); + return true; + } + // Update widgetspan data. + _colorSelectionRed( + selectedContentRange, + dataMap: widgetSpanSourceMap, + coloringChildSpan: true, + ); + // Re-create widgetspan. + if (count == 28) { // The index where the bulleted list begins. + insideSelection.add( + WidgetSpan( + child: Column( + children: [ + for (final MapEntry entry in widgetSpanSourceMap.entries) + Padding( + padding: const EdgeInsets.only(left: 20.0), + child: Text.rich( + widgetSpanSourceMap[entry.key]!, + ), + ) + ], + ), + ), + ); + } + count += (widgetSpanSourceMap.keys.last.endOffset - widgetSpanSourceMap.keys.first.startOffset).abs(); + return true; + } + return true; + }); + dataMap[entry.key] = TextSpan( + style: dataMap[entry.key]!.style, + children: [ + ...beforeSelection, + ...insideSelection, + ...afterSelection, + ], + ); + } + // Avoid clearing the selection and setting the state + // before we have colored all parts of the selection. + if (!coloringChildSpan) { + setState(() {}); + } + } + + @override + void initState() { + super.initState(); + _initData(); + } + + @override + void dispose() { + _selectionNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: Theme.of(context).colorScheme.inversePrimary, + title: Text(widget.title), + ), + body: SelectionArea( + key: selectionAreaKey, + child: MySelectableTextColumn( + selectionNotifier: _selectionNotifier, + dataSourceMap: dataSourceMap, + onChanged: _handleSelectableRegionStatusChanged, + ), + ), + floatingActionButton: FloatingActionButton( + onPressed: () { + setState(() { + // Resets the state to the origin data. + for (final MapEntry entry in originSourceData.entries) { + dataSourceMap[entry.key] = entry.value; + } + for (final MapEntry entry in originBulletSourceData.entries) { + bulletSourceMap[entry.key] = entry.value; + } + }); + }, + child: const Icon(Icons.undo), + ), + ); + } +} + +class MySelectableTextColumn extends StatefulWidget { + const MySelectableTextColumn({ + super.key, + required this.selectionNotifier, + required this.dataSourceMap, + required this.onChanged, + }); + + final SelectionListenerNotifier selectionNotifier; + final Map dataSourceMap; + final ValueChanged onChanged; + + @override + State createState() => _MySelectableTextColumnState(); +} + +class _MySelectableTextColumnState extends State { + ValueListenable? _selectableRegionScope; + + void _handleOnSelectableRegionChanged() { + if (_selectableRegionScope == null) { + return; + } + widget.onChanged.call(_selectableRegionScope!.value); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _selectableRegionScope?.removeListener(_handleOnSelectableRegionChanged); + _selectableRegionScope = SelectableRegionSelectionStatusScope.maybeOf(context); + _selectableRegionScope?.addListener(_handleOnSelectableRegionChanged); + } + + @override + void dispose() { + _selectableRegionScope?.removeListener(_handleOnSelectableRegionChanged); + _selectableRegionScope = null; + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return SelectionListener( + selectionNotifier: widget.selectionNotifier, + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + for (final MapEntry entry in widget.dataSourceMap.entries) + Text.rich( + entry.value, + ), + ], + ), + ), + ); + } +} diff --git a/examples/api/lib/material/slider/slider.0.dart b/examples/api/lib/material/slider/slider.0.dart index f73efb81c46..2c508b8c6af 100644 --- a/examples/api/lib/material/slider/slider.0.dart +++ b/examples/api/lib/material/slider/slider.0.dart @@ -5,11 +5,12 @@ import 'package:flutter/material.dart'; /// Flutter code sample for [Slider]. +/// set to false. -void main() => runApp(const SliderApp()); +void main() => runApp(const SliderExampleApp()); -class SliderApp extends StatelessWidget { - const SliderApp({super.key}); +class SliderExampleApp extends StatelessWidget { + const SliderExampleApp({super.key}); @override Widget build(BuildContext context) { @@ -28,21 +29,51 @@ class SliderExample extends StatefulWidget { class _SliderExampleState extends State { double _currentSliderValue = 20; + double _currentDiscreteSliderValue = 60; + bool year2023 = true; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Slider')), - body: Slider( - value: _currentSliderValue, - max: 100, - divisions: 5, - label: _currentSliderValue.round().toString(), - onChanged: (double value) { - setState(() { - _currentSliderValue = value; - }); - }, + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + spacing: 16, + children: [ + Slider( + year2023: year2023, + value: _currentSliderValue, + max: 100, + onChanged: (double value) { + setState(() { + _currentSliderValue = value; + }); + }, + ), + Slider( + year2023: year2023, + value: _currentDiscreteSliderValue, + max: 100, + divisions: 5, + label: _currentDiscreteSliderValue.round().toString(), + onChanged: (double value) { + setState(() { + _currentDiscreteSliderValue = value; + }); + }, + ), + SwitchListTile( + value: year2023, + title: year2023 ? const Text('Switch to latest M3 style') : const Text('Switch to year2023 M3 style'), + onChanged: (bool value) { + setState(() { + year2023 = !year2023; + }); + }, + ), + ], + ), ), ); } diff --git a/examples/api/lib/material/slider/slider.1.dart b/examples/api/lib/material/slider/slider.1.dart index f5c791fa111..b5716712cc5 100644 --- a/examples/api/lib/material/slider/slider.1.dart +++ b/examples/api/lib/material/slider/slider.1.dart @@ -13,12 +13,8 @@ class SliderApp extends StatelessWidget { @override Widget build(BuildContext context) { - return MaterialApp( - theme: ThemeData( - colorSchemeSeed: const Color(0xff6750a4), - useMaterial3: true, - ), - home: const SliderExample(), + return const MaterialApp( + home: SliderExample(), ); } } @@ -31,22 +27,36 @@ class SliderExample extends StatefulWidget { } class _SliderExampleState extends State { - double _currentSliderValue = 20; + double _currentSliderPrimaryValue = 0.2; + double _currentSliderSecondaryValue = 0.5; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Slider')), - body: Slider( - value: _currentSliderValue, - max: 100, - divisions: 5, - label: _currentSliderValue.round().toString(), - onChanged: (double value) { - setState(() { - _currentSliderValue = value; - }); - }, + body: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Slider( + value: _currentSliderPrimaryValue, + secondaryTrackValue: _currentSliderSecondaryValue, + label: _currentSliderPrimaryValue.round().toString(), + onChanged: (double value) { + setState(() { + _currentSliderPrimaryValue = value; + }); + }, + ), + Slider( + value: _currentSliderSecondaryValue, + label: _currentSliderSecondaryValue.round().toString(), + onChanged: (double value) { + setState(() { + _currentSliderSecondaryValue = value; + }); + }, + ), + ], ), ); } diff --git a/examples/api/lib/material/slider/slider.2.dart b/examples/api/lib/material/slider/slider.2.dart deleted file mode 100644 index b5716712cc5..00000000000 --- a/examples/api/lib/material/slider/slider.2.dart +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2014 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/material.dart'; - -/// Flutter code sample for [Slider]. - -void main() => runApp(const SliderApp()); - -class SliderApp extends StatelessWidget { - const SliderApp({super.key}); - - @override - Widget build(BuildContext context) { - return const MaterialApp( - home: SliderExample(), - ); - } -} - -class SliderExample extends StatefulWidget { - const SliderExample({super.key}); - - @override - State createState() => _SliderExampleState(); -} - -class _SliderExampleState extends State { - double _currentSliderPrimaryValue = 0.2; - double _currentSliderSecondaryValue = 0.5; - - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar(title: const Text('Slider')), - body: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Slider( - value: _currentSliderPrimaryValue, - secondaryTrackValue: _currentSliderSecondaryValue, - label: _currentSliderPrimaryValue.round().toString(), - onChanged: (double value) { - setState(() { - _currentSliderPrimaryValue = value; - }); - }, - ), - Slider( - value: _currentSliderSecondaryValue, - label: _currentSliderSecondaryValue.round().toString(), - onChanged: (double value) { - setState(() { - _currentSliderSecondaryValue = value; - }); - }, - ), - ], - ), - ); - } -} diff --git a/examples/api/lib/widgets/heroes/hero.1.dart b/examples/api/lib/widgets/heroes/hero.1.dart index 63d6931c38c..f71686208c3 100644 --- a/examples/api/lib/widgets/heroes/hero.1.dart +++ b/examples/api/lib/widgets/heroes/hero.1.dart @@ -18,9 +18,8 @@ class HeroApp extends StatelessWidget { @override Widget build(BuildContext context) { - return MaterialApp( - theme: ThemeData(useMaterial3: true), - home: const HeroExample(), + return const MaterialApp( + home: HeroExample(), ); } } diff --git a/examples/api/lib/widgets/safe_area/safe_area.0.dart b/examples/api/lib/widgets/safe_area/safe_area.0.dart new file mode 100644 index 00000000000..68795c4de72 --- /dev/null +++ b/examples/api/lib/widgets/safe_area/safe_area.0.dart @@ -0,0 +1,288 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/material.dart'; + +/// Flutter code sample for [SafeArea]. +/// +/// The app is wrapped with [Insets] (defined below) +/// to simulate a mobile device with a notched screen. + +void main() => runApp(const Insets()); + +class SafeAreaExampleApp extends StatelessWidget { + const SafeAreaExampleApp({super.key}); + + static const Color spring = Color(0xFF00FF80); + static final ColorScheme colors = ColorScheme.fromSeed(seedColor: spring); + static final ThemeData theme = ThemeData( + colorScheme: colors, + sliderTheme: SliderThemeData( + trackHeight: 8, + activeTrackColor: colors.primary.withValues(alpha: 0.5), + thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 12), + ), + scaffoldBackgroundColor: const Color(0xFFD0FFE8), + listTileTheme: const ListTileThemeData( + tileColor: Colors.white70, + visualDensity: VisualDensity(horizontal: -4, vertical: -4), + ), + appBarTheme: AppBarTheme( + backgroundColor: colors.secondary, + foregroundColor: colors.onSecondary, + ), + ); + + static final AppBar appBar = AppBar(title: const Text('SafeArea Demo')); + + @override + Widget build(BuildContext context) { + return MaterialApp( + theme: theme, + debugShowCheckedModeBanner: false, + home: Builder( + builder: (BuildContext context) => Scaffold( + appBar: Toggle.appBar.of(context) ? appBar : null, + body: const DefaultTextStyle( + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: Colors.black, + ), + child: Center( + child: SafeAreaExample(), + ), + ), + ), + ), + ); + } +} + +class SafeAreaExample extends StatelessWidget { + const SafeAreaExample({super.key}); + + static final Widget controls = Column( + children: [ + const SizedBox(height: 6), + Builder( + builder: (BuildContext context) => Text( + Toggle.safeArea.of(context) ? 'safe area!' : 'no safe area', + style: const TextStyle(fontSize: 24), + ), + ), + const Spacer(flex: 2), + for (final Value data in Value.allValues) ...data.controls, + ], + ); + + @override + Widget build(BuildContext context) { + final bool hasSafeArea = Toggle.safeArea.of(context); + + return SafeArea( + top: hasSafeArea, + bottom: hasSafeArea, + left: hasSafeArea, + right: hasSafeArea, + child: controls, + ); + } +} + +sealed class Value implements Enum { + Object _getValue(covariant Model model); + + List get controls; + + static const List allValues = [...Inset.values, ...Toggle.values]; +} + +enum Inset implements Value { + top('top notch'), + sides('side padding'), + bottom('bottom indicator'); + + const Inset(this.label); + + final String label; + + @override + double _getValue(_InsetModel model) => switch (this) { + top => model.insets.top, + sides => model.insets.left, + bottom => model.insets.bottom, + }; + + double of(BuildContext context) => _getValue(Model.of<_InsetModel>(context, this)); + + @override + List get controls => [ + Text(label), + Builder( + builder: (BuildContext context) => Slider( + max: 50, + value: of(context), + onChanged: (double newValue) { + InsetsState.instance.changeInset(this, newValue); + }, + ), + ), + const Spacer(), + ]; +} + +enum Toggle implements Value { + appBar('Build an AppBar?'), + safeArea("Wrap Scaffold's body with SafeArea?"); + + const Toggle(this.label); + + final String label; + + @override + bool _getValue(_ToggleModel model) => switch (this) { + appBar => model.buildAppBar, + safeArea => model.buildSafeArea, + }; + + bool of(BuildContext context) => _getValue(Model.of<_ToggleModel>(context, this)); + + @override + List get controls => [ + Builder( + builder: (BuildContext context) => SwitchListTile( + title: Text(label), + value: of(context), + onChanged: (bool value) { + InsetsState.instance.toggle(this, value); + }, + ), + ), + ]; +} + +abstract class Model extends InheritedModel { + const Model({super.key, required super.child}); + + static M of>(BuildContext context, Value value) { + return context.dependOnInheritedWidgetOfExactType(aspect: value)!; + } + + @override + bool updateShouldNotify(Model oldWidget) => true; + + @override + bool updateShouldNotifyDependent(Model oldWidget, Set dependencies) { + return dependencies.any((E data) => data._getValue(this) != data._getValue(oldWidget)); + } +} + +class _InsetModel extends Model { + const _InsetModel({required this.insets, required super.child}); + + final EdgeInsets insets; +} + +class _ToggleModel extends Model { + _ToggleModel({required Set togglers, required super.child}) + : buildAppBar = togglers.contains(Toggle.appBar), + buildSafeArea = togglers.contains(Toggle.safeArea); + + final bool buildAppBar; + final bool buildSafeArea; +} + +class Insets extends UniqueWidget { + const Insets() : super(key: const GlobalObjectKey('insets')); + + @override + InsetsState createState() => InsetsState(); +} + +class InsetsState extends State { + static InsetsState get instance => const Insets().currentState!; + + EdgeInsets insets = const EdgeInsets.fromLTRB(8, 25, 8, 12); + void changeInset(Inset inset, double value) { + setState(() { + insets = switch (inset) { + Inset.top => insets.copyWith(top: value), + Inset.sides => insets.copyWith(left: value, right: value), + Inset.bottom => insets.copyWith(bottom: value), + }; + }); + } + + final Set _togglers = {}; + void toggle(Toggle toggler, bool value) { + setState(() { + value ? _togglers.add(toggler) : _togglers.remove(toggler); + }); + } + + @override + Widget build(BuildContext context) { + final Widget topNotch = ClipRRect( + borderRadius: BorderRadius.vertical( + bottom: Radius.circular(insets.top), + ), + child: SizedBox( + height: insets.top, + child: const FractionallySizedBox( + widthFactor: 1 / 2, + child: ColoredBox(color: Colors.black), + ), + ), + ); + final Widget bottomIndicator = SizedBox( + width: double.infinity, + height: insets.bottom, + child: const FractionallySizedBox( + heightFactor: 0.5, + widthFactor: 0.5, + child: PhysicalShape( + clipper: ShapeBorderClipper(shape: StadiumBorder()), + color: Color(0xC0000000), + child: SizedBox.expand(), + ), + ), + ); + final Widget sideBar = SizedBox( + width: insets.left, + height: double.infinity, + child: const IgnorePointer(child: ColoredBox(color: Colors.black12)), + ); + + final Widget app = _ToggleModel( + togglers: _togglers, + child: Builder( + builder: (BuildContext context) => MediaQuery( + data: MediaQuery.of(context).copyWith( + viewInsets: EdgeInsets.only(top: insets.top), + viewPadding: insets, + padding: insets, + ), + child: const SafeAreaExampleApp(), + ), + ), + ); + + return _InsetModel( + insets: insets, + child: Directionality( + textDirection: TextDirection.ltr, + child: Stack( + children: [ + app, + Align(alignment: Alignment.topCenter, child: topNotch), + Align(alignment: Alignment.bottomCenter, child: bottomIndicator), + Align(alignment: Alignment.centerLeft, child: sideBar), + Align(alignment: Alignment.centerRight, child: sideBar), + ], + ), + ), + ); + } +} diff --git a/examples/api/lib/widgets/scroll_end_notification/scroll_end_notification.1.dart b/examples/api/lib/widgets/scroll_end_notification/scroll_end_notification.1.dart index 450e062b08d..3e6c3e68989 100644 --- a/examples/api/lib/widgets/scroll_end_notification/scroll_end_notification.1.dart +++ b/examples/api/lib/widgets/scroll_end_notification/scroll_end_notification.1.dart @@ -53,7 +53,7 @@ class _SliverAutoScrollExampleState extends State { // After an interactive scroll ends, if the alignedItem is partially visible // at the top or bottom of the viewport, then auto-scroll so that it's - // completely visible. To accomodate mouse-wheel scrolls and other small + // completely visible. To accommodate mouse-wheel scrolls and other small // adjustments, scrolls that change the scroll offset by less than // the alignedItem's extent don't trigger an auto-scroll. void maybeAutoScrollAlignedItem(RenderSliver alignedItem) { diff --git a/examples/api/lib/widgets/scroll_position/is_scrolling_listener.0.dart b/examples/api/lib/widgets/scroll_position/is_scrolling_listener.0.dart index 8ce8ea2bd92..22af0d363d3 100644 --- a/examples/api/lib/widgets/scroll_position/is_scrolling_listener.0.dart +++ b/examples/api/lib/widgets/scroll_position/is_scrolling_listener.0.dart @@ -56,7 +56,7 @@ class _IsScrollingListenerExampleState extends State } // After an interactive scroll "ends", auto-scroll so that last item in the - // viewport is completely visible. To accomodate mouse-wheel scrolls, other small + // viewport is completely visible. To accommodate mouse-wheel scrolls, other small // adjustments, and scrolling to the top, scrolls that put the scroll offset at // zero or change the scroll offset by less than itemExtent don't trigger // an auto-scroll. diff --git a/examples/api/lib/widgets/sliver/decorated_sliver.1.dart b/examples/api/lib/widgets/sliver/decorated_sliver.1.dart new file mode 100644 index 00000000000..13f59c53d12 --- /dev/null +++ b/examples/api/lib/widgets/sliver/decorated_sliver.1.dart @@ -0,0 +1,158 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/material.dart'; + +/// Flutter code example for [DecoratedSliver] +/// with clipping turned off in a parent [CustomScrollView]. + +void main() => runApp(const DecoratedSliverClipExampleApp()); + +class DecoratedSliverClipExampleApp extends StatelessWidget { + const DecoratedSliverClipExampleApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'DecoratedSliver Clip Example', + theme: ThemeData( + colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), + useMaterial3: true, + ), + home: const DecoratedSliverClipExample(), + ); + } +} + +class DecoratedSliverClipExample extends StatefulWidget { + const DecoratedSliverClipExample({super.key}); + + @override + State createState() => _DecoratedSliverClipExampleState(); +} + +class _DecoratedSliverClipExampleState extends State { + double _height = 225.0; + bool _isClipped = false; + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFF1C1C1C), + body: Column( + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Switch( + inactiveTrackColor: Colors.cyan, + activeColor: Colors.pink, + onChanged: (bool value) { + setState(() { + _isClipped = value; + }); + }, + value: _isClipped, + ), + Slider( + activeColor: Colors.pink, + inactiveColor: Colors.cyan, + onChanged: (double value) { + setState(() { + _height = value; + }); + }, + value: _height, + min: 150, + max: 225, + ), + ], + ), + const SizedBox( + height: 20.0, + ), + Stack( + children: [ + Padding( + padding: const EdgeInsets.all(24.0), + child: SizedBox( + width: 400, + height: _height, + child: ResizableCustomScrollView(isClipped: _isClipped), + ), + ), + Positioned( + top: _height, + left: 0, + right: 0, + child: SizedBox( + height: MediaQuery.of(context).size.height - _height, + width: double.infinity, + ), + ), + ], + ), + ], + ), + ); + } +} + +class ResizableCustomScrollView extends StatelessWidget { + const ResizableCustomScrollView({ + super.key, + required this.isClipped, + }); + + final bool isClipped; + + @override + Widget build(BuildContext context) { + return CustomScrollView( + // The clip behavior defaults to Clip.hardEdge if no argument is provided. + clipBehavior: isClipped ? Clip.hardEdge : Clip.none, + slivers: [ + DecoratedSliver( + decoration: const ShapeDecoration( + color: Color(0xFF2C2C2C), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.all( + Radius.circular(6), + ), + ), + shadows: [ + BoxShadow( + color: Colors.cyan, + offset: Offset(3, 3), + blurRadius: 24, + ), + ], + ), + sliver: SliverList.builder( + itemCount: 5, + itemBuilder: (_, int index) => Padding( + padding: const EdgeInsets.all(8.0), + child: Row( + children: [ + const Icon( + Icons.add_box, + color: Color(0xFFA8A8A8), + ), + Flexible( + child: Text( + 'Item $index', + style: const TextStyle( + color: Color(0xFFA8A8A8), + ), + ), + ), + ], + ), + ), + ), + ), + ], + ); + } +} diff --git a/examples/api/lib/widgets/sliver/pinned_header_sliver.1.dart b/examples/api/lib/widgets/sliver/pinned_header_sliver.1.dart index a340e5425e2..d2037eb88e3 100644 --- a/examples/api/lib/widgets/sliver/pinned_header_sliver.1.dart +++ b/examples/api/lib/widgets/sliver/pinned_header_sliver.1.dart @@ -45,7 +45,7 @@ class _SettingsAppBarExampleState extends State { // The key must be for a widget _below_ a RenderSliver so that // findAncestorRenderObjectOfType can find the RenderSliver when it searches - // the key widget's renderer ancesotrs. + // the key widget's renderer ancestors. RenderSliver? keyToSliver(GlobalKey key) => key.currentContext?.findAncestorRenderObjectOfType(); // Each time the app's list scrolls: if the Title sliver has scrolled completely behind diff --git a/examples/api/pubspec.yaml b/examples/api/pubspec.yaml index c8f76744872..5bc1d4db3c4 100644 --- a/examples/api/pubspec.yaml +++ b/examples/api/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: 'none' version: 1.0.0 environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 flutter: ">=2.5.0-6.0.pre.30 <3.0.0" dependencies: diff --git a/examples/api/test/material/color_scheme/dynamic_content_color.0_test.dart b/examples/api/test/material/color_scheme/dynamic_content_color.0_test.dart new file mode 100644 index 00000000000..e6d700cbfcd --- /dev/null +++ b/examples/api/test/material/color_scheme/dynamic_content_color.0_test.dart @@ -0,0 +1,181 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:io'; +import 'dart:math'; + +import 'package:flutter/material.dart'; +import 'package:flutter_api_samples/material/color_scheme/dynamic_content_color.0.dart' as example; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + final List<(ImageProvider, Brightness)> loadColorSchemeCalls = <(ImageProvider, Brightness)>[]; + + Future fakeColorSchemeLoader(ImageProvider provider, Brightness brightness) async { + loadColorSchemeCalls.add((provider, brightness)); + final int index = example.DynamicColorExample.images.indexOf(provider); + final int seedColor = 0xf * pow(0x10, index).toInt(); + return ColorScheme.fromSeed(seedColor: Color(seedColor), brightness: brightness); + } + + setUp(() { + loadColorSchemeCalls.clear(); + }); + + // The app being tested loads images via HTTP which the test + // framework defeats by default. + setUpAll(() { + HttpOverrides.global = null; + }); + + testWidgets('The content is visible', (WidgetTester tester) async { + await tester.pumpWidget( + example.DynamicColorExample( + loadColorScheme: fakeColorSchemeLoader, + ), + ); + await tester.pump(); + + expect( + find.widgetWithText(AppBar, 'Content Based Dynamic Color'), + findsOne, + ); + expect(find.byType(Switch), findsOne); + expect(find.byIcon(Icons.light_mode), findsOne); + + expect(find.text('Light ColorScheme'), findsOne); + expect(find.text('Dark ColorScheme'), findsOne); + expect(find.text('primary'), findsExactly(2)); + expect(find.text('onPrimary'), findsExactly(2)); + expect(find.text('primaryContainer'), findsExactly(2)); + expect(find.text('onPrimaryContainer'), findsExactly(2)); + expect(find.text('secondary'), findsExactly(2)); + expect(find.text('onSecondary'), findsExactly(2)); + expect(find.text('secondaryContainer'), findsExactly(2)); + expect(find.text('onSecondaryContainer'), findsExactly(2)); + expect(find.text('tertiary'), findsExactly(2)); + expect(find.text('onTertiary'), findsExactly(2)); + expect(find.text('tertiaryContainer'), findsExactly(2)); + expect(find.text('onTertiaryContainer'), findsExactly(2)); + expect(find.text('error'), findsExactly(2)); + expect(find.text('onError'), findsExactly(2)); + expect(find.text('errorContainer'), findsExactly(2)); + expect(find.text('onErrorContainer'), findsExactly(2)); + expect(find.text('surface'), findsExactly(2)); + expect(find.text('onSurface'), findsExactly(2)); + expect(find.text('onSurfaceVariant'), findsExactly(2)); + expect(find.text('outline'), findsExactly(2)); + expect(find.text('shadow'), findsExactly(2)); + expect(find.text('inverseSurface'), findsExactly(2)); + expect(find.text('onInverseSurface'), findsExactly(2)); + expect(find.text('inversePrimary'), findsExactly(2)); + + expect(loadColorSchemeCalls, hasLength(1)); + expect( + loadColorSchemeCalls.single.$1, + isA() + .having( + (NetworkImage provider) => provider.url, + 'url', + 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_1.png', + ), + ); + expect( + loadColorSchemeCalls.single.$2, + Brightness.light, + ); + + await tester.pumpAndSettle(); // Clears the timers from image loading. + }); + + testWidgets('The brightness can be changed', (WidgetTester tester) async { + await tester.pumpWidget( + example.DynamicColorExample( + loadColorScheme: fakeColorSchemeLoader, + ), + ); + await tester.pump(); + + expect(loadColorSchemeCalls, hasLength(1)); + expect( + loadColorSchemeCalls.single.$1, + isA() + .having( + (NetworkImage provider) => provider.url, + 'url', + 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_1.png', + ), + ); + expect( + loadColorSchemeCalls.single.$2, + Brightness.light, + ); + await tester.pump(); + await tester.pump(kThemeChangeDuration); + + ThemeData themeData = Theme.of(tester.element(find.byType(Scaffold))); + + expect(themeData.colorScheme.primary, const Color(0xff565992)); + expect(themeData.colorScheme.secondary, const Color(0xff5c5d72)); + + await tester.tap(find.byType(Switch)); + await tester.pump(); + + expect(loadColorSchemeCalls, hasLength(2)); + expect( + loadColorSchemeCalls.last.$1, + isA() + .having( + (NetworkImage provider) => provider.url, + 'url', + 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_1.png', + ), + ); + expect( + loadColorSchemeCalls.last.$2, + Brightness.dark, + ); + + await tester.pump(kThemeChangeDuration); + + themeData = Theme.of(tester.element(find.byType(Scaffold))); + + expect(themeData.colorScheme.primary, const Color(0xffbfc2ff)); + expect(themeData.colorScheme.secondary, const Color(0xffc5c4dd)); + }); + + testWidgets('Tapping an image loads a new color scheme', (WidgetTester tester) async { + await tester.pumpWidget( + example.DynamicColorExample( + loadColorScheme: fakeColorSchemeLoader, + ), + ); + await tester.pump(); + + await tester.tapAt(tester.getCenter(find.byType(Image).at(3))); + await tester.pump(); + + expect(loadColorSchemeCalls, hasLength(2)); + expect( + loadColorSchemeCalls.last.$1, + isA() + .having( + (NetworkImage provider) => provider.url, + 'url', + 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_4.png', + ), + ); + expect( + loadColorSchemeCalls.last.$2, + Brightness.light, + ); + + await tester.pump(kThemeChangeDuration); + + final ThemeData themeData = Theme.of(tester.element(find.byType(Scaffold))); + + expect(themeData.colorScheme.primary, const Color(0xff406836)); + expect(themeData.colorScheme.secondary, const Color(0xff54634d)); + }); +} diff --git a/examples/api/test/material/date_picker/date_picker_theme_day_shape.0_test.dart b/examples/api/test/material/date_picker/date_picker_theme_day_shape.0_test.dart index dc239d90494..cbaa88f15f3 100644 --- a/examples/api/test/material/date_picker/date_picker_theme_day_shape.0_test.dart +++ b/examples/api/test/material/date_picker/date_picker_theme_day_shape.0_test.dart @@ -14,6 +14,15 @@ void main() { const Color todayForegroundColor = Colors.black; const BorderSide todayBorder = BorderSide(width: 2); + ShapeDecoration? findDayDecoration(WidgetTester tester, String day) { + return tester.widget( + find.ancestor( + of: find.text(day), + matching: find.byType(Ink) + ), + ).decoration as ShapeDecoration?; + } + await tester.pumpWidget( const example.DatePickerApp(), ); @@ -21,21 +30,13 @@ void main() { await tester.tap(find.text('Open Date Picker')); await tester.pumpAndSettle(); - ShapeDecoration dayShapeDecoration = tester.widget(find.ancestor( - of: find.text('15'), - matching: find.byType(DecoratedBox), - )).decoration as ShapeDecoration; - // Test the current day shape decoration. + ShapeDecoration dayShapeDecoration = findDayDecoration(tester, '15')!; expect(dayShapeDecoration.color, todayBackgroundColor); expect(dayShapeDecoration.shape, dayShape.copyWith(side: todayBorder.copyWith(color: todayForegroundColor))); - dayShapeDecoration = tester.widget(find.ancestor( - of: find.text('20'), - matching: find.byType(DecoratedBox), - )).decoration as ShapeDecoration; - // Test the selected day shape decoration. + dayShapeDecoration = findDayDecoration(tester, '20')!; expect(dayShapeDecoration.color, theme.colorScheme.primary); expect(dayShapeDecoration.shape, dayShape); @@ -43,12 +44,8 @@ void main() { await tester.tap(find.text('15')); await tester.pumpAndSettle(); - dayShapeDecoration = tester.widget(find.ancestor( - of: find.text('15'), - matching: find.byType(DecoratedBox), - )).decoration as ShapeDecoration; - // Test the selected day shape decoration. + dayShapeDecoration = findDayDecoration(tester, '15')!; expect(dayShapeDecoration.color, todayBackgroundColor); expect(dayShapeDecoration.shape, dayShape.copyWith(side: todayBorder.copyWith(color: todayForegroundColor))); }); diff --git a/examples/api/test/material/navigation_bar/navigation_bar.1_test.dart b/examples/api/test/material/navigation_bar/navigation_bar.1_test.dart index 13005652c05..89d11c8efc5 100644 --- a/examples/api/test/material/navigation_bar/navigation_bar.1_test.dart +++ b/examples/api/test/material/navigation_bar/navigation_bar.1_test.dart @@ -38,6 +38,17 @@ void main() { expect(find.text('Label behavior: alwaysHide'), findsOneWidget); navigationBarWidget = tester.firstWidget(find.byType(NavigationBar)); - expect(navigationBarWidget.labelBehavior, NavigationDestinationLabelBehavior.alwaysHide); + expect( + navigationBarWidget.labelBehavior, + NavigationDestinationLabelBehavior.alwaysHide, + ); + }); + + testWidgets('Overflow buttons are aligned in the center', (WidgetTester tester) async { + await tester.pumpWidget(const example.NavigationBarApp()); + + final OverflowBar overflowBar = tester.widget(find.byType(OverflowBar)); + expect(overflowBar.overflowAlignment, OverflowBarAlignment.center); + expect(overflowBar.overflowSpacing, 10.0); }); } diff --git a/examples/api/test/material/page_transitions_theme/page_transitions_theme.3_test.dart b/examples/api/test/material/page_transitions_theme/page_transitions_theme.3_test.dart new file mode 100644 index 00000000000..418dade945e --- /dev/null +++ b/examples/api/test/material/page_transitions_theme/page_transitions_theme.3_test.dart @@ -0,0 +1,30 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/material.dart'; +import 'package:flutter_api_samples/material/page_transitions_theme/page_transitions_theme.3.dart' as example; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('Page transition', (WidgetTester tester) async { + await tester.pumpWidget( + const example.PageTransitionsThemeApp(), + ); + + final Finder homePage = find.byType(example.HomePage); + expect(homePage, findsOneWidget); + + final Finder kitten0 = find.widgetWithText(ListTile, 'Kitten 0'); + expect(kitten0, findsOneWidget); + + await tester.tap(kitten0); + await tester.pumpAndSettle(); + expect(find.widgetWithText(AppBar, 'Kitten 0'), findsOneWidget); + + await tester.tap(find.byType(BackButton)); + await tester.pumpAndSettle(); + + expect(find.widgetWithText(ListTile, 'Kitten 0'), findsOneWidget); + }); +} diff --git a/examples/api/test/material/progress_indicator/circular_progress_indicator.0_test.dart b/examples/api/test/material/progress_indicator/circular_progress_indicator.0_test.dart index 787acd9816a..b51cabf5191 100644 --- a/examples/api/test/material/progress_indicator/circular_progress_indicator.0_test.dart +++ b/examples/api/test/material/progress_indicator/circular_progress_indicator.0_test.dart @@ -2,23 +2,58 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:flutter/material.dart'; import 'package:flutter_api_samples/material/progress_indicator/circular_progress_indicator.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('Finds CircularProgressIndicator', (WidgetTester tester) async { + testWidgets('Determinate CircularProgressIndicator uses the provided value', (WidgetTester tester) async { await tester.pumpWidget( - const example.ProgressIndicatorApp(), + const example.ProgressIndicatorExampleApp(), + ); + await tester.pump(const Duration(milliseconds: 2500)); + + final Finder indicatorFinder = find.byType(CircularProgressIndicator).first; + final CircularProgressIndicator progressIndicator = tester.widget(indicatorFinder); + expect(progressIndicator.value, equals(0.5)); + }); + + testWidgets('Indeterminate CircularProgressIndicator does not have a value', (WidgetTester tester) async { + await tester.pumpWidget( + const example.ProgressIndicatorExampleApp(), + ); + await tester.pump(const Duration(milliseconds: 2500)); + + final Finder indicatorFinder = find.byType(CircularProgressIndicator).last; + final CircularProgressIndicator progressIndicator = tester.widget(indicatorFinder); + expect(progressIndicator.value, null); + }); + + testWidgets('Progress indicators year2023 flag can be toggled', (WidgetTester tester) async { + await tester.pumpWidget( + const example.ProgressIndicatorExampleApp(), ); - expect( - find.bySemanticsLabel('Circular progress indicator'), - findsOneWidget, + CircularProgressIndicator determinateIndicator = tester.widget( + find.byType(CircularProgressIndicator).first, ); + expect(determinateIndicator.year2023, true); + CircularProgressIndicator indeterminateIndicator = tester.widget( + find.byType(CircularProgressIndicator).last, + ); + expect(indeterminateIndicator.year2023, true); - // Test if CircularProgressIndicator is animating. - await tester.pump(const Duration(seconds: 2)); - expect(tester.hasRunningAnimations, isTrue); + await tester.tap(find.byType(SwitchListTile)); + await tester.pump(); + + determinateIndicator = tester.widget( + find.byType(CircularProgressIndicator).first, + ); + expect(determinateIndicator.year2023, false); + indeterminateIndicator = tester.widget( + find.byType(CircularProgressIndicator).last, + ); + expect(indeterminateIndicator.year2023, false); }); } diff --git a/examples/api/test/material/progress_indicator/circular_progress_indicator.1_test.dart b/examples/api/test/material/progress_indicator/circular_progress_indicator.1_test.dart index 8078c63c352..28ee53d40ae 100644 --- a/examples/api/test/material/progress_indicator/circular_progress_indicator.1_test.dart +++ b/examples/api/test/material/progress_indicator/circular_progress_indicator.1_test.dart @@ -10,7 +10,7 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Finds CircularProgressIndicator', (WidgetTester tester) async { await tester.pumpWidget( - const example.ProgressIndicatorApp(), + const example.ProgressIndicatorExampleApp(), ); expect( diff --git a/examples/api/test/material/progress_indicator/linear_progress_indicator.0_test.dart b/examples/api/test/material/progress_indicator/linear_progress_indicator.0_test.dart index 5f8b019f833..881b5139e61 100644 --- a/examples/api/test/material/progress_indicator/linear_progress_indicator.0_test.dart +++ b/examples/api/test/material/progress_indicator/linear_progress_indicator.0_test.dart @@ -8,33 +8,52 @@ import 'package:flutter_api_samples/material/progress_indicator/linear_progress_ import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('Determinate and Indeterminate LinearProgressIndicators', - (WidgetTester tester) async { + testWidgets('Determinate LinearProgressIndicator uses the provided value', (WidgetTester tester) async { + await tester.pumpWidget( + const example.ProgressIndicatorExampleApp(), + ); + await tester.pump(const Duration(milliseconds: 2500)); + + final Finder indicatorFinder = find.byType(LinearProgressIndicator).first; + final LinearProgressIndicator progressIndicator = tester.widget(indicatorFinder); + expect(progressIndicator.value, equals(0.5)); + }); + + testWidgets('Indeterminate LinearProgressIndicator does not have a value', (WidgetTester tester) async { + await tester.pumpWidget( + const example.ProgressIndicatorExampleApp(), + ); + await tester.pump(const Duration(milliseconds: 2500)); + + final Finder indicatorFinder = find.byType(LinearProgressIndicator).last; + final LinearProgressIndicator progressIndicator = tester.widget(indicatorFinder); + expect(progressIndicator.value, null); + }); + + testWidgets('Progress indicators year2023 flag can be toggled', (WidgetTester tester) async { await tester.pumpWidget( const example.ProgressIndicatorExampleApp(), ); - expect(find.text('Determinate LinearProgressIndicator'), findsOneWidget); - expect(find.text('Indeterminate LinearProgressIndicator'), findsOneWidget); - expect(find.byType(LinearProgressIndicator), findsNWidgets(2)); - - // Test determinate LinearProgressIndicator. - LinearProgressIndicator determinateIndicator = tester.firstWidget( + LinearProgressIndicator determinateIndicator = tester.widget( find.byType(LinearProgressIndicator).first, ); - expect(determinateIndicator.value, equals(0.0)); - - // Advance the animation by 2 seconds. - await tester.pump(const Duration(seconds: 2)); - determinateIndicator = tester.firstWidget( - find.byType(LinearProgressIndicator).first, - ); - expect(determinateIndicator.value, equals(0.4)); - - // Test indeterminate LinearProgressIndicator. - final LinearProgressIndicator indeterminateIndicator = tester.firstWidget( + expect(determinateIndicator.year2023, true); + LinearProgressIndicator indeterminateIndicator = tester.widget( find.byType(LinearProgressIndicator).last, ); - expect(indeterminateIndicator.value, null); + expect(indeterminateIndicator.year2023, true); + + await tester.tap(find.byType(SwitchListTile)); + await tester.pump(); + + determinateIndicator = tester.widget( + find.byType(LinearProgressIndicator).first, + ); + expect(determinateIndicator.year2023, false); + indeterminateIndicator = tester.widget( + find.byType(LinearProgressIndicator).last, + ); + expect(indeterminateIndicator.year2023, false); }); } diff --git a/examples/api/test/material/selection_area/selection_area.1_test.dart b/examples/api/test/material/selection_area/selection_area.1_test.dart new file mode 100644 index 00000000000..238c986d656 --- /dev/null +++ b/examples/api/test/material/selection_area/selection_area.1_test.dart @@ -0,0 +1,21 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/material.dart'; +import 'package:flutter_api_samples/material/selection_area/selection_area.1.dart' as example; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('SelectionArea SelectionListener Example Smoke Test', (WidgetTester tester) async { + await tester.pumpWidget( + const example.SelectionAreaSelectionListenerExampleApp(), + ); + expect(find.byType(Column), findsNWidgets(2)); + expect(find.textContaining('Selection StartOffset:'), findsOneWidget); + expect(find.textContaining('Selection EndOffset:'), findsOneWidget); + expect(find.textContaining('Selection Status:'), findsOneWidget); + expect(find.textContaining('Selectable Region Status:'), findsOneWidget); + expect(find.textContaining('This is some text under a SelectionArea that can be selected.'), findsOneWidget); + }); +} diff --git a/examples/api/test/material/selection_area/selection_area.2_test.dart b/examples/api/test/material/selection_area/selection_area.2_test.dart new file mode 100644 index 00000000000..319162ae2a8 --- /dev/null +++ b/examples/api/test/material/selection_area/selection_area.2_test.dart @@ -0,0 +1,125 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_api_samples/material/selection_area/selection_area.2.dart' as example; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('SelectionArea Color Text Red Example Smoke Test', (WidgetTester tester) async { + await tester.pumpWidget( + const example.SelectionAreaColorTextRedExampleApp(), + ); + expect(find.widgetWithIcon(FloatingActionButton, Icons.undo), findsOneWidget); + expect(find.byType(Column), findsNWidgets(2)); + expect(find.textContaining('This is some bulleted list:\n'), findsOneWidget); + for (int i = 1; i <= 7; i += 1) { + expect(find.widgetWithText(Text, '• Bullet $i'), findsOneWidget); + } + expect(find.textContaining('This is some text in a text widget.'), findsOneWidget); + expect(find.textContaining(' This is some more text in the same text widget.'), findsOneWidget); + expect(find.textContaining('This is some text in another text widget.'), findsOneWidget); + }); + + testWidgets('SelectionArea Color Text Red Example - colors selected range red', (WidgetTester tester) async { + await tester.pumpWidget( + const example.SelectionAreaColorTextRedExampleApp(), + ); + await tester.pumpAndSettle(); + final Finder paragraph1Finder = find.descendant(of: find.textContaining('This is some bulleted list').first, matching: find.byType(RichText).first); + final Finder paragraph3Finder = find.descendant(of: find.textContaining('This is some text in another text widget.'), matching: find.byType(RichText)); + final RenderParagraph paragraph1 = tester.renderObject(paragraph1Finder); + final List bullets = tester.renderObjectList(find.descendant(of: find.textContaining('• Bullet'), matching: find.byType(RichText))).toList(); + expect(bullets.length, 7); + final RenderParagraph paragraph2 = tester.renderObject(find.descendant(of: find.textContaining('This is some text in a text widget.'), matching: find.byType(RichText))); + final RenderParagraph paragraph3 = tester.renderObject(paragraph3Finder); + // Drag to select from paragraph 1 position 4 to paragraph 3 position 25. + final TestGesture gesture = await tester.startGesture(tester.getRect(paragraph1Finder).topLeft + const Offset(50.0, 10.0), kind: PointerDeviceKind.mouse); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.moveTo(tester.getRect(paragraph3Finder).centerLeft + const Offset(360.0, 0.0)); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + + // Verify selection. + // Bulleted list title. + expect(paragraph1.selections.length, 1); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 27)); + // Bulleted list. + for (final RenderParagraph paragraphBullet in bullets) { + expect(paragraphBullet.selections.length, 1); + expect(paragraphBullet.selections[0], const TextSelection(baseOffset: 0, extentOffset: 10)); + } + // Second text widget. + expect(paragraph2.selections.length, 1); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 83)); + // Third text widget. + expect(paragraph3.selections.length, 1); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 25)); + + // Color selection red. + expect(find.textContaining('Color Text Red'), findsOneWidget); + await tester.tap(find.textContaining('Color Text Red')); + await tester.pumpAndSettle(); + + // Verify selection is red. + final TextSpan paragraph1ResultingSpan = paragraph1.text as TextSpan; + final TextSpan paragraph2ResultingSpan = paragraph2.text as TextSpan; + final TextSpan paragraph3ResultingSpan = paragraph3.text as TextSpan; + // Title of bulleted list is partially red. + expect(paragraph1ResultingSpan.children, isNotNull); + expect(paragraph1ResultingSpan.children!.length, 1); + expect((paragraph1ResultingSpan.children![0] as TextSpan).children, isNotNull); + expect((paragraph1ResultingSpan.children![0] as TextSpan).children!.length, 3); + expect((paragraph1ResultingSpan.children![0] as TextSpan).children![0].style, isNull); + expect((paragraph1ResultingSpan.children![0] as TextSpan).children![1], isA()); + expect(((paragraph1ResultingSpan.children![0] as TextSpan).children![1] as TextSpan).text, isNotNull); + expect(((paragraph1ResultingSpan.children![0] as TextSpan).children![1] as TextSpan).text, ' is some bulleted list:\n'); + expect((paragraph1ResultingSpan.children![0] as TextSpan).children![1].style, isNotNull); + expect((paragraph1ResultingSpan.children![0] as TextSpan).children![1].style!.color, isNotNull); + expect((paragraph1ResultingSpan.children![0] as TextSpan).children![1].style!.color, Colors.red); + expect((paragraph1ResultingSpan.children![0] as TextSpan).children![2], isA()); + // Bullets are red. + for (final RenderParagraph paragraphBullet in bullets) { + final TextSpan resultingBulletSpan = paragraphBullet.text as TextSpan; + expect(resultingBulletSpan.children, isNotNull); + expect(resultingBulletSpan.children!.length, 1); + expect(resultingBulletSpan.children![0], isA()); + expect((resultingBulletSpan.children![0] as TextSpan).children, isNotNull); + expect((resultingBulletSpan.children![0] as TextSpan).children!.length, 1); + expect((resultingBulletSpan.children![0] as TextSpan).children![0], isA()); + expect(((resultingBulletSpan.children![0] as TextSpan).children![0] as TextSpan).style, isNotNull); + expect(((resultingBulletSpan.children![0] as TextSpan).children![0] as TextSpan).style!.color, isNotNull); + expect(((resultingBulletSpan.children![0] as TextSpan).children![0] as TextSpan).style!.color, Colors.red); + } + // Second text widget is red. + expect(paragraph2ResultingSpan.children, isNotNull); + expect(paragraph2ResultingSpan.children!.length, 1); + expect(paragraph2ResultingSpan.children![0], isA()); + expect((paragraph2ResultingSpan.children![0] as TextSpan).children, isNotNull); + for (final InlineSpan span in (paragraph2ResultingSpan.children![0] as TextSpan).children!) { + if (span is TextSpan) { + expect(span.style, isNotNull); + expect(span.style!.color, isNotNull); + expect(span.style!.color, Colors.red); + } + } + // Part of third text widget is red. + expect(paragraph3ResultingSpan.children, isNotNull); + expect(paragraph3ResultingSpan.children!.length, 1); + expect(paragraph3ResultingSpan.children![0], isA()); + expect((paragraph3ResultingSpan.children![0] as TextSpan).children, isNotNull); + expect((paragraph3ResultingSpan.children![0] as TextSpan).children!.length, 2); + expect((paragraph3ResultingSpan.children![0] as TextSpan).children![0], isA()); + expect(((paragraph3ResultingSpan.children![0] as TextSpan).children![0] as TextSpan).text, isNotNull); + expect(((paragraph3ResultingSpan.children![0] as TextSpan).children![0] as TextSpan).text, 'This is some text in ano'); + expect((paragraph3ResultingSpan.children![0] as TextSpan).children![0].style, isNotNull); + expect((paragraph3ResultingSpan.children![0] as TextSpan).children![0].style!.color, isNotNull); + expect((paragraph3ResultingSpan.children![0] as TextSpan).children![0].style!.color, Colors.red); + expect((paragraph3ResultingSpan.children![0] as TextSpan).children![1].style, isNull); + }); +} diff --git a/examples/api/test/material/slider/slider.0_test.dart b/examples/api/test/material/slider/slider.0_test.dart index 8ab403e3eb0..9db8e95f59d 100644 --- a/examples/api/test/material/slider/slider.0_test.dart +++ b/examples/api/test/material/slider/slider.0_test.dart @@ -7,23 +7,50 @@ import 'package:flutter_api_samples/material/slider/slider.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('Slider can change its value', (WidgetTester tester) async { + testWidgets('Sliders can change their value', (WidgetTester tester) async { await tester.pumpWidget( - const example.SliderApp(), + const example.SliderExampleApp(), ); - expect(find.byType(Slider), findsOneWidget); + expect(find.byType(Slider), findsNWidgets(2)); - final Finder sliderFinder = find.byType(Slider); + Finder sliderFinder = find.byType(Slider).first; + Slider slider = tester.widget(sliderFinder); + expect(slider.value, equals(20)); - Slider slider = tester.widget(sliderFinder); - expect(slider.value, 20); - - final Offset center = tester.getCenter(sliderFinder); - await tester.tapAt(Offset(center.dx + 100, center.dy)); + await tester.tapAt(tester.getCenter(sliderFinder)); await tester.pump(); slider = tester.widget(sliderFinder); - expect(slider.value, 60.0); + expect(slider.value, equals(50)); + + sliderFinder = find.byType(Slider).last; + slider = tester.widget(sliderFinder); + expect(slider.value, equals(60)); + + await tester.tapAt(tester.getTopLeft(sliderFinder)); + await tester.pump(); + + slider = tester.widget(sliderFinder); + expect(slider.value, equals(0)); + }); + + testWidgets('Sliders year2023 flag can be toggled', (WidgetTester tester) async { + await tester.pumpWidget( + const example.SliderExampleApp(), + ); + + Slider slider = tester.widget(find.byType(Slider).first); + expect(slider.year2023, true); + Slider discreteSlider = tester.widget(find.byType(Slider).last); + expect(discreteSlider.year2023, true); + + await tester.tap(find.byType(SwitchListTile)); + await tester.pumpAndSettle(); + + slider = tester.widget(find.byType(Slider).first); + expect(slider.year2023, false); + discreteSlider = tester.widget(find.byType(Slider).last); + expect(discreteSlider.year2023, false); }); } diff --git a/examples/api/test/material/slider/slider.1_test.dart b/examples/api/test/material/slider/slider.1_test.dart index 3cdfc5cdb7c..9096c90b008 100644 --- a/examples/api/test/material/slider/slider.1_test.dart +++ b/examples/api/test/material/slider/slider.1_test.dart @@ -7,23 +7,29 @@ import 'package:flutter_api_samples/material/slider/slider.1.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('Slider can change its value', (WidgetTester tester) async { + testWidgets('Slider shows secondary track', (WidgetTester tester) async { await tester.pumpWidget( const example.SliderApp(), ); - expect(find.byType(Slider), findsOneWidget); + expect(find.byType(Slider), findsNWidgets(2)); - final Finder sliderFinder = find.byType(Slider); + final Finder slider1Finder = find.byType(Slider).at(0); + final Finder slider2Finder = find.byType(Slider).at(1); - Slider slider = tester.widget(sliderFinder); - expect(slider.value, 20); + Slider slider1 = tester.widget(slider1Finder); + Slider slider2 = tester.widget(slider2Finder); + expect(slider1.secondaryTrackValue, slider2.value); - final Offset center = tester.getCenter(sliderFinder); - await tester.tapAt(Offset(center.dx + 100, center.dy)); + const double targetValue = 0.8; + final Rect rect = tester.getRect(slider2Finder); + final Offset target = Offset(rect.left + (rect.right - rect.left) * targetValue, rect.top + (rect.bottom - rect.top) / 2); + await tester.tapAt(target); await tester.pump(); - slider = tester.widget(sliderFinder); - expect(slider.value, 60.0); + slider1 = tester.widget(slider1Finder); + slider2 = tester.widget(slider2Finder); + expect(slider1.secondaryTrackValue, closeTo(targetValue, 0.05)); + expect(slider1.secondaryTrackValue, slider2.value); }); } diff --git a/examples/api/test/material/slider/slider.2_test.dart b/examples/api/test/material/slider/slider.2_test.dart deleted file mode 100644 index 1ec99374587..00000000000 --- a/examples/api/test/material/slider/slider.2_test.dart +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2014 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/material.dart'; -import 'package:flutter_api_samples/material/slider/slider.2.dart' as example; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - testWidgets('Slider shows secondary track', (WidgetTester tester) async { - await tester.pumpWidget( - const example.SliderApp(), - ); - - expect(find.byType(Slider), findsNWidgets(2)); - - final Finder slider1Finder = find.byType(Slider).at(0); - final Finder slider2Finder = find.byType(Slider).at(1); - - Slider slider1 = tester.widget(slider1Finder); - Slider slider2 = tester.widget(slider2Finder); - expect(slider1.secondaryTrackValue, slider2.value); - - const double targetValue = 0.8; - final Rect rect = tester.getRect(slider2Finder); - final Offset target = Offset(rect.left + (rect.right - rect.left) * targetValue, rect.top + (rect.bottom - rect.top) / 2); - await tester.tapAt(target); - await tester.pump(); - - slider1 = tester.widget(slider1Finder); - slider2 = tester.widget(slider2Finder); - expect(slider1.secondaryTrackValue, closeTo(targetValue, 0.05)); - expect(slider1.secondaryTrackValue, slider2.value); - }); -} diff --git a/examples/api/test/widgets/safe_area/safe_area.0_test.dart b/examples/api/test/widgets/safe_area/safe_area.0_test.dart new file mode 100644 index 00000000000..38f772a9cf5 --- /dev/null +++ b/examples/api/test/widgets/safe_area/safe_area.0_test.dart @@ -0,0 +1,113 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/material.dart'; +import 'package:flutter_api_samples/widgets/safe_area/safe_area.0.dart' as example; +import 'package:flutter_test/flutter_test.dart'; + +example.InsetsState get insetsState => example.InsetsState.instance; + +void main() { + testWidgets('SafeArea widget count', (WidgetTester tester) async { + await tester.pumpWidget(const example.Insets()); + + // 1 SafeArea and 2 ListTile widgets. + expect(find.byType(SafeArea), findsNWidgets(3)); + + insetsState.toggle(example.Toggle.appBar, true); + await tester.pump(); + expect(find.byType(SafeArea), findsNWidgets(4)); + }); + + testWidgets('ListTile removes side padding from its content', (WidgetTester tester) async { + await tester.pumpWidget(const example.Insets()); + + late BuildContext context; + late EdgeInsets padding; + + final Finder findBody = find.byType(example.SafeAreaExample); + final Finder findListTile = find.text(example.Toggle.appBar.label).first; + + context = tester.element(findBody); + padding = MediaQuery.paddingOf(context); + expect(padding.top, greaterThan(0)); + expect(padding.bottom, greaterThan(0)); + expect(padding.left, greaterThan(0)); + expect(padding.right, greaterThan(0)); + + context = tester.element(findListTile); + padding = MediaQuery.paddingOf(context); + expect(padding.top, greaterThan(0)); + expect(padding.bottom, greaterThan(0)); + expect(padding.left, 0); + expect(padding.right, 0); + }); + + testWidgets('AppBar removes top padding of Scaffold body', (WidgetTester tester) async { + await tester.pumpWidget(const example.Insets()); + final BuildContext context = tester.element(find.text('no safe area')); + + // Double-check that side & bottom padding are unchanged. + void verifySidesAndBottom() { + final EdgeInsets padding = MediaQuery.paddingOf(context); + expect(padding.left, example.Inset.sides.of(context)); + expect(padding.right, example.Inset.sides.of(context)); + expect(padding.bottom, example.Inset.bottom.of(context)); + } + + final double topInset = example.Inset.top.of(context); + expect(topInset, greaterThan(0)); + expect(MediaQuery.paddingOf(context).top, topInset); + verifySidesAndBottom(); + + insetsState.toggle(example.Toggle.appBar, true); + await tester.pump(); + + expect(example.Inset.top.of(context), greaterThan(0)); + expect(MediaQuery.paddingOf(context).top, 0); + verifySidesAndBottom(); + }); + + testWidgets('SafeArea removes all padding', (WidgetTester tester) async { + await tester.pumpWidget(const example.Insets()); + + BuildContext context = tester.element(find.text('no safe area')); + expect(MediaQuery.paddingOf(context), insetsState.insets); + + insetsState.toggle(example.Toggle.safeArea, true); + await tester.pump(); + + context = tester.element(find.text('safe area!')); + expect(MediaQuery.paddingOf(context), EdgeInsets.zero); + }); + + // Regression test for https://github.com/flutter/flutter/issues/159340. + testWidgets('App displays without layout issues', (WidgetTester tester) async { + // Set the app's size to to match the default DartPad demo screen. + await tester.pumpWidget( + const Center( + child: SizedBox( + width: 500.0, + height: 480.0, + child: example.Insets(), + ), + ), + ); + + double appScreenHeight() => tester.getRect(find.byType(example.Insets)).height; + + expect(appScreenHeight(), 480); + expect(insetsState.insets, const EdgeInsets.fromLTRB(8.0, 25.0, 8.0, 12.0)); + + // Drag each slider to its maximum value. + for (int index = 0; index < 3; index++) { + await tester.drag(find.byType(Slider).at(index), const Offset(500.0, 0.0)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + } + + expect(appScreenHeight(), 480); + expect(insetsState.insets, const EdgeInsets.all(50)); + }); +} diff --git a/examples/api/test/widgets/scroll_end_notification/scroll_end_notification.1_test.dart b/examples/api/test/widgets/scroll_end_notification/scroll_end_notification.1_test.dart index 8f36c8fde5d..edb8c10663f 100644 --- a/examples/api/test/widgets/scroll_end_notification/scroll_end_notification.1_test.dart +++ b/examples/api/test/widgets/scroll_end_notification/scroll_end_notification.1_test.dart @@ -15,7 +15,7 @@ void main() { final double itemHeight = tester.getSize(find.widgetWithText(Card, 'Item 0.15')).height; // The scroll view is 600 pixels high and the big orange - // "AlignedItem" is precedeed by 15 regular items. Scroll up enough + // "AlignedItem" is preceded by 15 regular items. Scroll up enough // to make it partially visible. await tester.drag(find.byType(CustomScrollView), Offset(0, 600 - 15.5 * itemHeight)); await tester.pumpAndSettle(); diff --git a/examples/api/test/widgets/shortcuts/shortcuts.1_test.dart b/examples/api/test/widgets/shortcuts/shortcuts.1_test.dart index a6b2b7362fa..3e280bde60a 100644 --- a/examples/api/test/widgets/shortcuts/shortcuts.1_test.dart +++ b/examples/api/test/widgets/shortcuts/shortcuts.1_test.dart @@ -55,7 +55,7 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/issues/156806. - testWidgets('SingleActivator is used instead of LogiccalKeySet', (WidgetTester tester) async { + testWidgets('SingleActivator is used instead of LogicalKeySet', (WidgetTester tester) async { await tester.pumpWidget( const example.ShortcutsExampleApp(), ); diff --git a/examples/api/test/widgets/sliver/decorated_sliver.1_test.dart b/examples/api/test/widgets/sliver/decorated_sliver.1_test.dart new file mode 100644 index 00000000000..7f3611216cf --- /dev/null +++ b/examples/api/test/widgets/sliver/decorated_sliver.1_test.dart @@ -0,0 +1,42 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/material.dart'; +import 'package:flutter_api_samples/widgets/sliver/decorated_sliver.1.dart' as example; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('CustomScrollView clipBehavior is Clip.none when is Clipped is false', (WidgetTester tester) async { + await tester.pumpWidget( + const MaterialApp( + home: example.DecoratedSliverClipExample(), + ), + ); + + final CustomScrollView customScrollView = tester.widget(find.byType(CustomScrollView)); + + expect(customScrollView.clipBehavior, equals(Clip.none)); + }); + + testWidgets('Verify the DecoratedSliver has shadow property in decoration', (WidgetTester tester) async { + await tester.pumpWidget( + const MaterialApp( + home: example.ResizableCustomScrollView(isClipped: false), + ), + ); + + final DecoratedSliver decoratedSliver = tester.widget(find.byType(DecoratedSliver)); + final ShapeDecoration shapeDecoration = decoratedSliver.decoration as ShapeDecoration; + + expect(shapeDecoration.shadows, isNotEmpty); + }); + + testWidgets('Verify Slider and Switch widgets', (WidgetTester tester) async { + await tester.pumpWidget(const example.DecoratedSliverClipExampleApp()); + + expect(find.byType(Slider), findsOneWidget); + + expect(find.byType(Switch), findsOneWidget); + }); +} diff --git a/examples/api/test/widgets/sliver/sliver_main_axis_group.0_test.dart b/examples/api/test/widgets/sliver/sliver_main_axis_group.0_test.dart index 563b54739d8..4bf4e15abec 100644 --- a/examples/api/test/widgets/sliver/sliver_main_axis_group.0_test.dart +++ b/examples/api/test/widgets/sliver/sliver_main_axis_group.0_test.dart @@ -19,7 +19,16 @@ void main() { final RenderSliverPersistentHeader renderAppBar = tester.renderObject(find.byType(SliverAppBar)); final RenderSliverList renderSliverList = tester.renderObject(find.byType(SliverList)); - final RenderSliverToBoxAdapter renderSliverAdapter = tester.renderObject(find.byType(SliverToBoxAdapter)); + final RenderSliverToBoxAdapter renderSliverAdapter = tester.renderObject( + find.descendant( + of: find.byType(SliverMainAxisGroup), + matching: find.byType( + SliverToBoxAdapter, + skipOffstage: false, + ), + skipOffstage: false, + ), + ); // renderAppBar, renderSliverList, and renderSliverAdapter1 are part of the same sliver group. expect(renderAppBar.geometry!.scrollExtent, equals(70.0)); diff --git a/examples/flutter_view/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/examples/flutter_view/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index e67b2808af0..4f746537f28 100644 --- a/examples/flutter_view/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/examples/flutter_view/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -50,6 +50,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/examples/flutter_view/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/examples/flutter_view/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index a7d8ce3a9a3..394ad7ac6d5 100644 --- a/examples/flutter_view/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/examples/flutter_view/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -48,6 +48,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/examples/flutter_view/pubspec.yaml b/examples/flutter_view/pubspec.yaml index 16b533b75ee..a8413a31e5f 100644 --- a/examples/flutter_view/pubspec.yaml +++ b/examples/flutter_view/pubspec.yaml @@ -2,7 +2,7 @@ name: flutter_view description: A new flutter project. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/examples/hello_world/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/examples/hello_world/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index e67b2808af0..4f746537f28 100644 --- a/examples/hello_world/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/examples/hello_world/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -50,6 +50,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/examples/hello_world/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/examples/hello_world/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index aa9d3f928d0..86297218ed5 100644 --- a/examples/hello_world/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/examples/hello_world/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -48,6 +48,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/examples/hello_world/pubspec.yaml b/examples/hello_world/pubspec.yaml index 8c04ebfc47a..cb0d88e4f16 100644 --- a/examples/hello_world/pubspec.yaml +++ b/examples/hello_world/pubspec.yaml @@ -1,7 +1,7 @@ name: hello_world environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/examples/image_list/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/examples/image_list/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index a00db7a9e12..4430d329ff9 100644 --- a/examples/image_list/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/examples/image_list/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -52,6 +52,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/examples/image_list/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/examples/image_list/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 95ef0b61381..dcc468c2fe5 100644 --- a/examples/image_list/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/examples/image_list/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -48,6 +48,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/examples/image_list/pubspec.yaml b/examples/image_list/pubspec.yaml index bd99b1e859d..abfbf66ffbb 100644 --- a/examples/image_list/pubspec.yaml +++ b/examples/image_list/pubspec.yaml @@ -4,7 +4,7 @@ description: Simple Flutter project used for benchmarking image loading over net version: 1.0.0+1 environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/examples/layers/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/examples/layers/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index e67b2808af0..4f746537f28 100644 --- a/examples/layers/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/examples/layers/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -50,6 +50,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/examples/layers/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/examples/layers/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index fcb264ef5f0..467bcf77769 100644 --- a/examples/layers/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/examples/layers/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -48,6 +48,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/examples/layers/pubspec.yaml b/examples/layers/pubspec.yaml index e022afb88a2..2798e4662be 100644 --- a/examples/layers/pubspec.yaml +++ b/examples/layers/pubspec.yaml @@ -1,7 +1,7 @@ name: flutter_examples_layers environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/examples/platform_channel/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/examples/platform_channel/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index e67b2808af0..4f746537f28 100644 --- a/examples/platform_channel/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/examples/platform_channel/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -50,6 +50,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/examples/platform_channel/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/examples/platform_channel/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 8d923f3b2bb..bd565a55746 100644 --- a/examples/platform_channel/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/examples/platform_channel/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -48,6 +48,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/examples/platform_channel/pubspec.yaml b/examples/platform_channel/pubspec.yaml index 7f6fa24ae0e..989491c3563 100644 --- a/examples/platform_channel/pubspec.yaml +++ b/examples/platform_channel/pubspec.yaml @@ -1,7 +1,7 @@ name: platform_channel environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/examples/platform_channel_swift/pubspec.yaml b/examples/platform_channel_swift/pubspec.yaml index b932b57644f..1be21ff6b90 100644 --- a/examples/platform_channel_swift/pubspec.yaml +++ b/examples/platform_channel_swift/pubspec.yaml @@ -1,7 +1,7 @@ name: platform_channel_swift environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/examples/platform_view/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/examples/platform_view/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 0e9c6c70279..488dfea4966 100644 --- a/examples/platform_view/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/examples/platform_view/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -59,6 +59,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/examples/platform_view/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/examples/platform_view/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index cbcf3c2dd48..81415a252a8 100644 --- a/examples/platform_view/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/examples/platform_view/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -48,6 +48,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/examples/platform_view/pubspec.yaml b/examples/platform_view/pubspec.yaml index 695d2496aa3..61a3e9c0d80 100644 --- a/examples/platform_view/pubspec.yaml +++ b/examples/platform_view/pubspec.yaml @@ -1,7 +1,7 @@ name: platform_view environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/examples/splash/pubspec.yaml b/examples/splash/pubspec.yaml index 3da8f8b1a15..8014616776c 100644 --- a/examples/splash/pubspec.yaml +++ b/examples/splash/pubspec.yaml @@ -1,7 +1,7 @@ name: splash environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/examples/texture/pubspec.yaml b/examples/texture/pubspec.yaml index 6654ba5c60f..bdd6a790457 100644 --- a/examples/texture/pubspec.yaml +++ b/examples/texture/pubspec.yaml @@ -1,7 +1,7 @@ name: texture environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/packages/flutter/lib/services.dart b/packages/flutter/lib/services.dart index 4516577f8ff..acad47fa013 100644 --- a/packages/flutter/lib/services.dart +++ b/packages/flutter/lib/services.dart @@ -44,6 +44,7 @@ export 'src/services/raw_keyboard_macos.dart'; export 'src/services/raw_keyboard_web.dart'; export 'src/services/raw_keyboard_windows.dart'; export 'src/services/restoration.dart'; +export 'src/services/scribe.dart'; export 'src/services/service_extensions.dart'; export 'src/services/spell_check.dart'; export 'src/services/system_channels.dart'; diff --git a/packages/flutter/lib/src/animation/animation_controller.dart b/packages/flutter/lib/src/animation/animation_controller.dart index c946b447d66..d6592f75f0c 100644 --- a/packages/flutter/lib/src/animation/animation_controller.dart +++ b/packages/flutter/lib/src/animation/animation_controller.dart @@ -383,8 +383,8 @@ class AnimationController extends Animation /// * [stop], which aborts the animation without changing its value or status /// and without dispatching any notifications other than completing or /// canceling the [TickerFuture]. - /// * [forward], [reverse], [animateTo], [animateWith], [fling], and [repeat], - /// which start the animation controller. + /// * [forward], [reverse], [animateTo], [animateWith], [animateBackWith], + /// [fling], and [repeat], which start the animation controller. set value(double newValue) { stop(); _internalSetValue(newValue); @@ -802,6 +802,7 @@ class AnimationController extends Animation /// Drives the animation according to the given simulation. /// + /// {@template flutter.animation.AnimationController.animateWith} /// The values from the simulation are clamped to the [lowerBound] and /// [upperBound]. To avoid this, consider creating the [AnimationController] /// using the [AnimationController.unbounded] constructor. @@ -811,9 +812,15 @@ class AnimationController extends Animation /// The most recently returned [TickerFuture], if any, is marked as having been /// canceled, meaning the future never completes and its [TickerFuture.orCancel] /// derivative future completes with a [TickerCanceled] error. + /// {@endtemplate} /// /// The [status] is always [AnimationStatus.forward] for the entire duration /// of the simulation. + /// + /// See also: + /// + /// * [animateBackWith], which is like this method but the status is always + /// [AnimationStatus.reverse]. TickerFuture animateWith(Simulation simulation) { assert( _ticker != null, @@ -825,6 +832,29 @@ class AnimationController extends Animation return _startSimulation(simulation); } + /// Drives the animation according to the given simulation with a [status] of + /// [AnimationStatus.reverse]. + /// + /// {@macro flutter.animation.AnimationController.animateWith} + /// + /// The [status] is always [AnimationStatus.reverse] for the entire duration + /// of the simulation. + /// + /// See also: + /// + /// * [animateWith], which is like this method but the status is always + /// [AnimationStatus.forward]. + TickerFuture animateBackWith(Simulation simulation) { + assert( + _ticker != null, + 'AnimationController.animateWith() called after AnimationController.dispose()\n' + 'AnimationController methods should not be used after calling dispose.', + ); + stop(); + _direction = _AnimationDirection.reverse; + return _startSimulation(simulation); + } + TickerFuture _startSimulation(Simulation simulation) { assert(!isAnimating); _simulation = simulation; diff --git a/packages/flutter/lib/src/animation/listener_helpers.dart b/packages/flutter/lib/src/animation/listener_helpers.dart index acecaa12fb6..4813a0caf6a 100644 --- a/packages/flutter/lib/src/animation/listener_helpers.dart +++ b/packages/flutter/lib/src/animation/listener_helpers.dart @@ -91,7 +91,7 @@ mixin AnimationEagerListenerMixin { /// and [didUnregisterListener]. Implementations of these methods can be obtained /// by mixing in another mixin from this library, such as [AnimationLazyListenerMixin]. mixin AnimationLocalListenersMixin { - final ObserverList _listeners = ObserverList(); + final HashedObserverList _listeners = HashedObserverList(); /// Called immediately before a listener is added via [addListener]. /// diff --git a/packages/flutter/lib/src/cupertino/app.dart b/packages/flutter/lib/src/cupertino/app.dart index cfb848dc766..772314f8e3a 100644 --- a/packages/flutter/lib/src/cupertino/app.dart +++ b/packages/flutter/lib/src/cupertino/app.dart @@ -534,18 +534,51 @@ class _CupertinoAppState extends State { ]; } - Widget _inspectorSelectButtonBuilder(BuildContext context, VoidCallback onPressed) { - return CupertinoButton.filled( + Widget _exitWidgetSelectionButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + required GlobalKey key, + }) { + return CupertinoButton( + key: key, + color: _widgetSelectionButtonsBackgroundColor(context), padding: EdgeInsets.zero, onPressed: onPressed, - child: const Icon( - CupertinoIcons.search, + child: Icon( + CupertinoIcons.xmark, size: 28.0, - color: CupertinoColors.white, + color: _widgetSelectionButtonsForegroundColor(context), + semanticLabel: 'Exit Select Widget mode.', ), ); } + Widget _moveExitWidgetSelectionButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + bool isLeftAligned = true, + }) { + return CupertinoButton( + onPressed: onPressed, + padding: EdgeInsets.zero, + child: Icon( + isLeftAligned ? CupertinoIcons.arrow_right : CupertinoIcons.arrow_left, + size: 32.0, + color: _widgetSelectionButtonsBackgroundColor(context), + semanticLabel: + 'Move "Exit Select Widget mode" button to the ${isLeftAligned ? 'right' : 'left'}.', + ), + ); + } + + Color _widgetSelectionButtonsForegroundColor(BuildContext context) { + return CupertinoTheme.of(context).primaryContrastingColor; + } + + Color _widgetSelectionButtonsBackgroundColor(BuildContext context) { + return CupertinoTheme.of(context).primaryColor; + } + WidgetsApp _buildWidgetApp(BuildContext context) { final CupertinoThemeData effectiveThemeData = CupertinoTheme.of(context); final Color color = CupertinoDynamicColor.resolve(widget.color ?? effectiveThemeData.primaryColor, context); @@ -572,7 +605,9 @@ class _CupertinoAppState extends State { showPerformanceOverlay: widget.showPerformanceOverlay, showSemanticsDebugger: widget.showSemanticsDebugger, debugShowCheckedModeBanner: widget.debugShowCheckedModeBanner, - inspectorSelectButtonBuilder: _inspectorSelectButtonBuilder, + exitWidgetSelectionButtonBuilder: _exitWidgetSelectionButtonBuilder, + moveExitWidgetSelectionButtonBuilder: + _moveExitWidgetSelectionButtonBuilder, shortcuts: widget.shortcuts, actions: widget.actions, restorationScopeId: widget.restorationScopeId, @@ -606,7 +641,9 @@ class _CupertinoAppState extends State { showPerformanceOverlay: widget.showPerformanceOverlay, showSemanticsDebugger: widget.showSemanticsDebugger, debugShowCheckedModeBanner: widget.debugShowCheckedModeBanner, - inspectorSelectButtonBuilder: _inspectorSelectButtonBuilder, + exitWidgetSelectionButtonBuilder: _exitWidgetSelectionButtonBuilder, + moveExitWidgetSelectionButtonBuilder: + _moveExitWidgetSelectionButtonBuilder, shortcuts: widget.shortcuts, actions: widget.actions, restorationScopeId: widget.restorationScopeId, diff --git a/packages/flutter/lib/src/cupertino/colors.dart b/packages/flutter/lib/src/cupertino/colors.dart index 7425b59d429..c9a4410ac34 100644 --- a/packages/flutter/lib/src/cupertino/colors.dart +++ b/packages/flutter/lib/src/cupertino/colors.dart @@ -611,7 +611,7 @@ abstract final class CupertinoColors { highContrastColor: Color.fromARGB(94, 60, 60, 67), darkHighContrastColor: Color.fromARGB(173, 84, 84, 88), elevatedColor: Color.fromARGB(73, 60, 60, 67), - darkElevatedColor: Color.fromARGB(153, 84, 84, 88), + darkElevatedColor: Color.fromARGB(153, 210, 210, 210), highContrastElevatedColor: Color.fromARGB(94, 60, 60, 67), darkHighContrastElevatedColor: Color.fromARGB(173, 84, 84, 88), ); diff --git a/packages/flutter/lib/src/cupertino/dialog.dart b/packages/flutter/lib/src/cupertino/dialog.dart index 56c07493861..8300e9bd37f 100644 --- a/packages/flutter/lib/src/cupertino/dialog.dart +++ b/packages/flutter/lib/src/cupertino/dialog.dart @@ -79,7 +79,6 @@ const TextStyle _kActionSheetContentStyle = TextStyle( ); // Generic constants shared between Dialog and ActionSheet. -const double _kBlurAmount = 20.0; const double _kCornerRadius = 14.0; const double _kDividerThickness = 0.3; @@ -115,7 +114,7 @@ const double _kActionSheetButtonVerticalPaddingBase = 1.8; // Extracted from https://developer.apple.com/design/resources/. const Color _kDialogColor = CupertinoDynamicColor.withBrightness( color: Color(0xCCF2F2F2), - darkColor: Color(0xBF1E1E1E), + darkColor: Color(0xCC2D2D2D), ); // Translucent light gray that is painted on top of the blurred backdrop as the @@ -123,7 +122,7 @@ const Color _kDialogColor = CupertinoDynamicColor.withBrightness( // Eyeballed from iOS 13 beta simulator. const Color _kDialogPressedColor = CupertinoDynamicColor.withBrightness( color: Color(0xFFE1E1E1), - darkColor: Color(0xFF2E2E2E), + darkColor: Color(0xFF404040), ); // Translucent light gray that is painted on top of the blurred backdrop as the @@ -494,20 +493,34 @@ class _CupertinoAlertDialogState extends State { } } -/// Rounded rectangle surface that looks like an iOS popup surface, e.g., alert dialog -/// and action sheet. +/// An iOS-style component for creating modal overlays like dialogs and action +/// sheets. /// -/// A [CupertinoPopupSurface] can be configured to paint or not paint a white -/// color on top of its blurred area. Typical usage should paint white on top -/// of the blur. However, the white paint can be disabled for the purpose of -/// rendering divider gaps for a more complicated layout, e.g., [CupertinoAlertDialog]. -/// Additionally, the white paint can be disabled to render a blurred rounded -/// rectangle without any color (similar to iOS's volume control popup). +/// By default, [CupertinoPopupSurface] generates a rounded rectangle surface +/// that applies two effects to the background content: +/// +/// 1. Background filter: Saturates and then blurs content behind the surface. +/// 2. Overlay color: Covers the filtered background with a transparent +/// surface color. The color adapts to the CupertinoTheme's brightness: +/// light gray when the ambient [CupertinoTheme] brightness is +/// [Brightness.light], and dark gray when [Brightness.dark]. +/// +/// The blur strength can be changed by setting [blurSigma] to a positive value, +/// or removed by setting the [blurSigma] to 0. +/// +/// The saturation effect can be removed for debugging by setting +/// [debugIsVibrancePainted] to false. The saturation effect is not supported on +/// web with the skwasm renderer and will not be applied regardless of the value +/// of [debugIsVibrancePainted]. +/// +/// The surface color can be disabled by setting [isSurfacePainted] to false, +/// which is useful for more complicated layouts, such as rendering divider gaps +/// in [CupertinoAlertDialog] or rendering custom surface colors. /// /// {@tool dartpad} /// This sample shows how to use a [CupertinoPopupSurface]. The [CupertinoPopupSurface] -/// shows a model popup from the bottom of the screen. -/// Toggling the switch to configure its surface color. +/// shows a modal popup from the bottom of the screen. +/// Toggle the switch to configure its surface color. /// /// ** See code in examples/api/lib/cupertino/dialog/cupertino_popup_surface.0.dart ** /// {@end-tool} @@ -521,9 +534,17 @@ class CupertinoPopupSurface extends StatelessWidget { /// Creates an iOS-style rounded rectangle popup surface. const CupertinoPopupSurface({ super.key, + this.blurSigma = defaultBlurSigma, this.isSurfacePainted = true, - this.child, - }); + required this.child, + }) : assert(blurSigma >= 0, 'CupertinoPopupSurface requires a non-negative blur sigma.'); + + /// The strength of the gaussian blur applied to the area beneath this + /// surface. + /// + /// Defaults to [defaultBlurSigma]. Setting [blurSigma] to 0 will remove the + /// blur filter. + final double blurSigma; /// Whether or not to paint a translucent white on top of this surface's /// blurred background. [isSurfacePainted] should be true for a typical popup @@ -533,26 +554,158 @@ class CupertinoPopupSurface extends StatelessWidget { /// Some popups, like iOS's volume control popup, choose to render a blurred /// area without any white paint covering it. To achieve this effect, /// [isSurfacePainted] should be set to false. + /// + /// Defaults to true. final bool isSurfacePainted; /// The widget below this widget in the tree. - final Widget? child; + // Because [CupertinoPopupSurface] is composed of proxy boxes, which mimic + // the size of their child, a [child] is required to ensure that this surface + // has a size. + final Widget child; + + /// The default strength of the blur applied to widgets underlying a + /// [CupertinoPopupSurface]. + /// + /// Eyeballed from the iOS 17 simulator. + static const double defaultBlurSigma = 30.0; + + /// The default corner radius of a [CupertinoPopupSurface]. + static const BorderRadius _clipper = BorderRadius.all(Radius.circular(14)); + + // The [ColorFilter] matrix used to saturate widgets underlying a + // [CupertinoPopupSurface] when the ambient [CupertinoThemeData.brightness] is + // [Brightness.light]. + // + // To derive this matrix, the saturation matrix was taken from + // https://docs.rainmeter.net/tips/colormatrix-guide/ and was tweaked to + // resemble the iOS 17 simulator. + // + // The matrix can be derived from the following function: + // static List get _lightSaturationMatrix { + // const double lightLumR = 0.26; + // const double lightLumG = 0.4; + // const double lightLumB = 0.17; + // const double saturation = 2.0; + // const double sr = (1 - saturation) * lightLumR; + // const double sg = (1 - saturation) * lightLumG; + // const double sb = (1 - saturation) * lightLumB; + // return [ + // sr + saturation, sg, sb, 0.0, 0.0, + // sr, sg + saturation, sb, 0.0, 0.0, + // sr, sg, sb + saturation, 0.0, 0.0, + // 0.0, 0.0, 0.0, 1.0, 0.0, + // ]; + // } + static const List _lightSaturationMatrix = [ + 1.74, -0.40, -0.17, 0.00, 0.00, + -0.26, 1.60, -0.17, 0.00, 0.00, + -0.26, -0.40, 1.83, 0.00, 0.00, + 0.00, 0.00, 0.00, 1.00, 0.00 + ]; + + // The [ColorFilter] matrix used to saturate widgets underlying a + // [CupertinoPopupSurface] when the ambient [CupertinoThemeData.brightness] is + // [Brightness.dark]. + // + // To derive this matrix, the saturation matrix was taken from + // https://docs.rainmeter.net/tips/colormatrix-guide/ and was tweaked to + // resemble the iOS 17 simulator. + // + // The matrix can be derived from the following function: + // static List get _darkSaturationMatrix { + // const double additive = 0.3; + // const double darkLumR = 0.45; + // const double darkLumG = 0.8; + // const double darkLumB = 0.16; + // const double saturation = 1.7; + // const double sr = (1 - saturation) * darkLumR; + // const double sg = (1 - saturation) * darkLumG; + // const double sb = (1 - saturation) * darkLumB; + // return [ + // sr + saturation, sg, sb, 0.0, additive, + // sr, sg + saturation, sb, 0.0, additive, + // sr, sg, sb + saturation, 0.0, additive, + // 0.0, 0.0, 0.0, 1.0, 0.0, + // ]; + // } + static const List _darkSaturationMatrix = [ + 1.39, -0.56, -0.11, 0.00, 0.30, + -0.32, 1.14, -0.11, 0.00, 0.30, + -0.32, -0.56, 1.59, 0.00, 0.30, + 0.00, 0.00, 0.00, 1.00, 0.00 + ]; + + /// Whether or not the area beneath this surface should be saturated with a + /// [ColorFilter]. + /// + /// The appearance of the [ColorFilter] is determined by the [Brightness] + /// value obtained from the ambient [CupertinoTheme]. + /// + /// The vibrance is always painted if asserts are disabled. + /// + /// Defaults to true. + static bool debugIsVibrancePainted = true; + + ImageFilter? _buildFilter(Brightness? brightness) { + bool isVibrancePainted = true; + assert(() { + isVibrancePainted = debugIsVibrancePainted; + return true; + }()); + if ((kIsWeb && !isSkiaWeb) || !isVibrancePainted) { + if (blurSigma == 0) { + return null; + } + return ImageFilter.blur( + sigmaX: blurSigma, + sigmaY: blurSigma, + ); + } + + final ColorFilter colorFilter = switch (brightness) { + Brightness.dark => const ColorFilter.matrix(_darkSaturationMatrix), + Brightness.light || null => const ColorFilter.matrix(_lightSaturationMatrix) + }; + + if (blurSigma == 0) { + return colorFilter; + } + + return ImageFilter.compose( + inner: colorFilter, + outer: ImageFilter.blur( + sigmaX: blurSigma, + sigmaY: blurSigma, + ), + ); + } @override Widget build(BuildContext context) { - Widget? contents = child; + final ImageFilter? filter = _buildFilter(CupertinoTheme.maybeBrightnessOf(context)); + Widget contents = child; + if (isSurfacePainted) { contents = ColoredBox( color: CupertinoDynamicColor.resolve(_kDialogColor, context), child: contents, ); } + + if (filter != null) { + return ClipRRect( + borderRadius: _clipper, + child: BackdropFilter( + filter: filter, + child: contents, + ), + ); + } + return ClipRRect( - borderRadius: const BorderRadius.all(Radius.circular(_kCornerRadius)), - child: BackdropFilter( - filter: ImageFilter.blur(sigmaX: _kBlurAmount, sigmaY: _kBlurAmount), - child: contents, - ), + borderRadius: _clipper, + child: contents, ); } } @@ -1138,7 +1291,10 @@ class _CupertinoActionSheetState extends State { child: ClipRRect( borderRadius: const BorderRadius.all(Radius.circular(12.0)), child: BackdropFilter( - filter: ImageFilter.blur(sigmaX: _kBlurAmount, sigmaY: _kBlurAmount), + filter: ImageFilter.blur( + sigmaX: CupertinoPopupSurface.defaultBlurSigma, + sigmaY: CupertinoPopupSurface.defaultBlurSigma, + ), child: _ActionSheetMainSheet( pressedIndex: _pressedIndex, onPressedUpdate: _onPressedUpdate, @@ -1215,6 +1371,7 @@ class CupertinoActionSheetAction extends StatefulWidget { required this.onPressed, this.isDefaultAction = false, this.isDestructiveAction = false, + this.mouseCursor, required this.child, }); @@ -1234,6 +1391,12 @@ class CupertinoActionSheetAction extends StatefulWidget { /// Destructive buttons have red text. final bool isDestructiveAction; + /// The cursor that will be shown when hovering over the button. + /// + /// If null, defaults to [SystemMouseCursors.click] on web and + /// [MouseCursor.defer] on other platforms. + final MouseCursor? mouseCursor; + /// The widget below this widget in the tree. /// /// Typically a [Text] widget. @@ -1312,7 +1475,7 @@ class _CupertinoActionSheetActionState extends State + fontSize * _kActionSheetButtonVerticalPaddingFactor; return MouseRegion( - cursor: kIsWeb ? SystemMouseCursors.click : MouseCursor.defer, + cursor: widget.mouseCursor ?? (kIsWeb ? SystemMouseCursors.click : MouseCursor.defer), child: MetaData( metaData: this, behavior: HitTestBehavior.opaque, diff --git a/packages/flutter/lib/src/cupertino/magnifier.dart b/packages/flutter/lib/src/cupertino/magnifier.dart index cf749f5ca60..9713a97f7af 100644 --- a/packages/flutter/lib/src/cupertino/magnifier.dart +++ b/packages/flutter/lib/src/cupertino/magnifier.dart @@ -6,8 +6,11 @@ library; import 'dart:math' as math; + import 'package:flutter/widgets.dart'; +import 'theme.dart'; + /// A [CupertinoMagnifier] used for magnifying text in cases where a user's /// finger may be blocking the point of interest, like a selection handle. /// @@ -215,6 +218,7 @@ class _CupertinoTextMagnifierState extends State @override Widget build(BuildContext context) { + final CupertinoThemeData themeData = CupertinoTheme.of(context); return AnimatedPositioned( duration: CupertinoTextMagnifier._kDragAnimationDuration, curve: widget.animationCurve, @@ -223,6 +227,10 @@ class _CupertinoTextMagnifierState extends State child: CupertinoMagnifier( inOutAnimation: _ioAnimation, additionalFocalPointOffset: Offset(0, _verticalFocalPointAdjustment), + borderSide: BorderSide( + color: themeData.primaryColor, + width: 2.0, + ), ), ); } @@ -252,7 +260,7 @@ class CupertinoMagnifier extends StatelessWidget { /// Creates a [RawMagnifier] in the Cupertino style. /// /// The default constructor parameters and constants were eyeballed on - /// an iPhone XR iOS v15.5. + /// an iPhone 16 iOS v18.1. const CupertinoMagnifier({ super.key, this.size = kDefaultSize, @@ -268,7 +276,10 @@ class CupertinoMagnifier extends StatelessWidget { ], this.clipBehavior = Clip.none, this.borderSide = - const BorderSide(color: Color.fromARGB(255, 232, 232, 232)), + const BorderSide( + color: Color.fromARGB(255, 0, 124, 255), + width: 2.0, + ), this.inOutAnimation, this.magnificationScale = 1.0, }) : assert(magnificationScale > 0, 'The magnification scale should be greater than zero.'); diff --git a/packages/flutter/lib/src/cupertino/route.dart b/packages/flutter/lib/src/cupertino/route.dart index 390bac8b41e..0b40b4aa35a 100644 --- a/packages/flutter/lib/src/cupertino/route.dart +++ b/packages/flutter/lib/src/cupertino/route.dart @@ -20,6 +20,7 @@ import 'dart:ui' show ImageFilter; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; +import 'package:flutter/physics.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; @@ -175,6 +176,12 @@ mixin CupertinoRouteTransitionMixin on PageRoute { ((nextRoute is CupertinoRouteTransitionMixin) || nextRouteHasDelegatedTransition); } + @override + bool canTransitionFrom(TransitionRoute previousRoute) { + // Supress previous route from transitioning if this is a fullscreenDialog route. + return previousRoute is PageRoute && !fullscreenDialog; + } + @override Widget buildPage(BuildContext context, Animation animation, Animation secondaryAnimation) { final Widget child = buildContent(context); @@ -1059,6 +1066,30 @@ class _CupertinoEdgeShadowPainter extends BoxPainter { } } +// The stiffness used by dialogs and action sheets. +// +// The stiffness value is obtained by examining the properties of +// `CASpringAnimation` in Xcode. The damping value is derived similarly, with +// additional precision calculated based on `_kStandardStiffness` to ensure a +// damping ratio of 1 (critically damped): damping = 2 * sqrt(stiffness) +const double _kStandardStiffness = 522.35; +const double _kStandardDamping = 45.7099552; +const SpringDescription _kStandardSpring = SpringDescription( + mass: 1, + stiffness: _kStandardStiffness, + damping: _kStandardDamping, +); +// The iOS spring animation duration is 0.404 seconds, based on the properties +// of `CASpringAnimation` in Xcode. At this point, the spring's position +// `x(0.404)` is approximately 0.9990000, suggesting that iOS uses a position +// tolerance of 1e-3 (matching the default `_epsilonDefault` value). +// +// However, the spring's velocity `dx(0.404)` is about 0.02, indicating that iOS +// may not consider velocity when determining the animation's end condition. To +// account for this, a larger velocity tolerance is applied here for added +// safety. +const Tolerance _kStandardTolerance = Tolerance(velocity: 0.03); + /// A route that shows a modal iOS-style popup that slides up from the /// bottom of the screen. /// @@ -1138,29 +1169,21 @@ class CupertinoModalPopupRoute extends PopupRoute { @override Duration get transitionDuration => _kModalPopupTransitionDuration; - CurvedAnimation? _animation; - - late Tween _offsetTween; - /// {@macro flutter.widgets.DisplayFeatureSubScreen.anchorPoint} final Offset? anchorPoint; @override - Animation createAnimation() { - assert(_animation == null); - _animation = CurvedAnimation( - parent: super.createAnimation(), - - // These curves were initially measured from native iOS horizontal page - // route animations and seemed to be a good match here as well. - curve: Curves.linearToEaseOut, - reverseCurve: Curves.linearToEaseOut.flipped, + Simulation createSimulation({ required bool forward }) { + assert(!debugTransitionCompleted(), 'Cannot reuse a $runtimeType after disposing it.'); + final double end = forward ? 1.0 : 0.0; + return SpringSimulation( + _kStandardSpring, + controller!.value, + end, + 0, + tolerance: _kStandardTolerance, + snapToEnd: true, ); - _offsetTween = Tween( - begin: const Offset(0.0, 1.0), - end: Offset.zero, - ); - return _animation!; } @override @@ -1179,17 +1202,16 @@ class CupertinoModalPopupRoute extends PopupRoute { return Align( alignment: Alignment.bottomCenter, child: FractionalTranslation( - translation: _offsetTween.evaluate(_animation!), + translation: _offsetTween.evaluate(animation), child: child, ), ); } - @override - void dispose() { - _animation?.dispose(); - super.dispose(); - } + static final Tween _offsetTween = Tween( + begin: const Offset(0.0, 1.0), + end: Offset.zero, + ); } /// Shows a modal iOS-style popup that slides up from the bottom of the screen. @@ -1280,12 +1302,6 @@ Future showCupertinoModalPopup({ ); } -// The curve and initial scale values were mostly eyeballed from iOS, however -// they reuse the same animation curve that was modeled after native page -// transitions. -final Animatable _dialogScaleTween = Tween(begin: 1.3, end: 1.0) - .chain(CurveTween(curve: Curves.linearToEaseOut)); - Widget _buildCupertinoDialogTransitions(BuildContext context, Animation animation, Animation secondaryAnimation, Widget child) { return child; } @@ -1433,33 +1449,36 @@ class CupertinoDialogRoute extends RawDialogRoute { CurvedAnimation? _fadeAnimation; @override - Widget buildTransitions(BuildContext context, Animation animation, Animation secondaryAnimation, Widget child) { + Simulation createSimulation({ required bool forward }) { + assert(!debugTransitionCompleted(), 'Cannot reuse a $runtimeType after disposing it.'); + final double end = forward ? 1.0 : 0.0; + return SpringSimulation( + _kStandardSpring, + controller!.value, + end, + 0, + tolerance: _kStandardTolerance, + snapToEnd: true, + ); + } + @override + Widget buildTransitions(BuildContext context, Animation animation, Animation secondaryAnimation, Widget child) { if (transitionBuilder != null) { return super.buildTransitions(context, animation, secondaryAnimation, child); } - if (_fadeAnimation?.parent != animation) { - _fadeAnimation?.dispose(); - _fadeAnimation = CurvedAnimation( - parent: animation, - curve: Curves.easeInOut, - ); - } - - final CurvedAnimation fadeAnimation = _fadeAnimation!; - if (animation.status == AnimationStatus.reverse) { return FadeTransition( - opacity: fadeAnimation, - child: super.buildTransitions(context, animation, secondaryAnimation, child), + opacity: animation, + child: child, ); } return FadeTransition( - opacity: fadeAnimation, + opacity: animation, child: ScaleTransition( scale: animation.drive(_dialogScaleTween), - child: super.buildTransitions(context, animation, secondaryAnimation, child), + child: child, ), ); } @@ -1469,4 +1488,9 @@ class CupertinoDialogRoute extends RawDialogRoute { _fadeAnimation?.dispose(); super.dispose(); } + + // The curve and initial scale values were mostly eyeballed from iOS, however + // they reuse the same animation curve that was modeled after native page + // transitions. + static final Tween _dialogScaleTween = Tween(begin: 1.3, end: 1.0); } diff --git a/packages/flutter/lib/src/cupertino/sliding_segmented_control.dart b/packages/flutter/lib/src/cupertino/sliding_segmented_control.dart index 281dd1886a5..6c1eba481a4 100644 --- a/packages/flutter/lib/src/cupertino/sliding_segmented_control.dart +++ b/packages/flutter/lib/src/cupertino/sliding_segmented_control.dart @@ -1280,7 +1280,7 @@ class _RenderSegmentedControl extends RenderBox for (int index = 0; index < children.length; index += 2) { // Children contains both segment and separator and the order is segment -> - // separator -> segment. So to paint separators, indes should start from 0 and + // separator -> segment. So to paint separators, index should start from 0 and // the step should be 2. _paintChild(context, offset, children[index]); } diff --git a/packages/flutter/lib/src/cupertino/text_field.dart b/packages/flutter/lib/src/cupertino/text_field.dart index 1527397c341..f034c9ea662 100644 --- a/packages/flutter/lib/src/cupertino/text_field.dart +++ b/packages/flutter/lib/src/cupertino/text_field.dart @@ -295,7 +295,12 @@ class CupertinoTextField extends StatefulWidget { this.contentInsertionConfiguration, this.clipBehavior = Clip.hardEdge, this.restorationId, + @Deprecated( + 'Use `stylusHandwritingEnabled` instead. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) this.scribbleEnabled = true, + this.stylusHandwritingEnabled = EditableText.defaultStylusHandwritingEnabled, this.enableIMEPersonalizedLearning = true, this.contextMenuBuilder = _defaultContextMenuBuilder, this.spellCheckConfiguration, @@ -425,7 +430,12 @@ class CupertinoTextField extends StatefulWidget { this.contentInsertionConfiguration, this.clipBehavior = Clip.hardEdge, this.restorationId, + @Deprecated( + 'Use `stylusHandwritingEnabled` instead. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) this.scribbleEnabled = true, + this.stylusHandwritingEnabled = true, this.enableIMEPersonalizedLearning = true, this.contextMenuBuilder = _defaultContextMenuBuilder, this.spellCheckConfiguration, @@ -762,8 +772,15 @@ class CupertinoTextField extends StatefulWidget { final String? restorationId; /// {@macro flutter.widgets.editableText.scribbleEnabled} + @Deprecated( + 'Use `stylusHandwritingEnabled` instead. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) final bool scribbleEnabled; + /// {@macro flutter.widgets.editableText.stylusHandwritingEnabled} + final bool stylusHandwritingEnabled; + /// {@macro flutter.services.TextInputConfiguration.enableIMEPersonalizedLearning} final bool enableIMEPersonalizedLearning; @@ -895,6 +912,7 @@ class CupertinoTextField extends StatefulWidget { properties.add(EnumProperty('textDirection', textDirection, defaultValue: null)); properties.add(DiagnosticsProperty('clipBehavior', clipBehavior, defaultValue: Clip.hardEdge)); properties.add(DiagnosticsProperty('scribbleEnabled', scribbleEnabled, defaultValue: true)); + properties.add(DiagnosticsProperty('stylusHandwritingEnabled', stylusHandwritingEnabled, defaultValue: EditableText.defaultStylusHandwritingEnabled)); properties.add(DiagnosticsProperty('enableIMEPersonalizedLearning', enableIMEPersonalizedLearning, defaultValue: true)); properties.add(DiagnosticsProperty('spellCheckConfiguration', spellCheckConfiguration, defaultValue: null)); properties.add(DiagnosticsProperty>('contentCommitMimeTypes', contentInsertionConfiguration?.allowedMimeTypes ?? const [], defaultValue: contentInsertionConfiguration == null ? const [] : kDefaultContentInsertionMimeTypes)); @@ -1286,13 +1304,13 @@ class _CupertinoTextFieldState extends State with Restoratio TextSelectionControls? textSelectionControls = widget.selectionControls; VoidCallback? handleDidGainAccessibilityFocus; + VoidCallback? handleDidLoseAccessibilityFocus; switch (defaultTargetPlatform) { case TargetPlatform.iOS: case TargetPlatform.android: case TargetPlatform.fuchsia: - case TargetPlatform.linux: textSelectionControls ??= cupertinoTextSelectionHandleControls; - + case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: textSelectionControls ??= cupertinoDesktopTextSelectionHandleControls; @@ -1302,6 +1320,9 @@ class _CupertinoTextFieldState extends State with Restoratio _effectiveFocusNode.requestFocus(); } }; + handleDidLoseAccessibilityFocus = () { + _effectiveFocusNode.unfocus(); + }; } final bool enabled = widget.enabled; @@ -1447,6 +1468,7 @@ class _CupertinoTextFieldState extends State with Restoratio clipBehavior: widget.clipBehavior, restorationId: 'editable', scribbleEnabled: widget.scribbleEnabled, + stylusHandwritingEnabled: widget.stylusHandwritingEnabled, enableIMEPersonalizedLearning: widget.enableIMEPersonalizedLearning, contentInsertionConfiguration: widget.contentInsertionConfiguration, contextMenuBuilder: widget.contextMenuBuilder, @@ -1465,6 +1487,7 @@ class _CupertinoTextFieldState extends State with Restoratio _requestKeyboard(); }, onDidGainAccessibilityFocus: handleDidGainAccessibilityFocus, + onDidLoseAccessibilityFocus: handleDidLoseAccessibilityFocus, onFocus: enabled ? () { assert( diff --git a/packages/flutter/lib/src/cupertino/text_form_field_row.dart b/packages/flutter/lib/src/cupertino/text_form_field_row.dart index bde43c299d1..80b1ccab0a7 100644 --- a/packages/flutter/lib/src/cupertino/text_form_field_row.dart +++ b/packages/flutter/lib/src/cupertino/text_form_field_row.dart @@ -157,6 +157,7 @@ class CupertinoTextFormFieldRow extends FormField { color: CupertinoColors.placeholderText, ), EditableTextContextMenuBuilder? contextMenuBuilder = _defaultContextMenuBuilder, + SpellCheckConfiguration? spellCheckConfiguration, super.restorationId, }) : assert(initialValue == null || controller == null), assert(obscuringCharacter.length == 1), @@ -234,6 +235,7 @@ class CupertinoTextFormFieldRow extends FormField { placeholder: placeholder, placeholderStyle: placeholderStyle, contextMenuBuilder: contextMenuBuilder, + spellCheckConfiguration: spellCheckConfiguration ), ), ); diff --git a/packages/flutter/lib/src/foundation/diagnostics.dart b/packages/flutter/lib/src/foundation/diagnostics.dart index 5d50c0ef22a..30f9f417ea1 100644 --- a/packages/flutter/lib/src/foundation/diagnostics.dart +++ b/packages/flutter/lib/src/foundation/diagnostics.dart @@ -8,6 +8,7 @@ /// @docImport 'package:flutter/widgets.dart'; library; +import 'dart:collection'; import 'dart:math' as math; import 'dart:ui' show clampDouble; @@ -1421,6 +1422,17 @@ class TextTreeRenderer { } } +/// The JSON representation of a [DiagnosticsNode]. +typedef _JsonDiagnosticsNode = Map; + +/// Stack containing [DiagnosticNode]s to convert to JSON and the callback to +/// call with the JSON. +/// +/// Using a stack is required to process the widget tree iteratively instead of +/// recursively. +typedef _NodesToJsonifyStack + = ListQueue<(DiagnosticsNode, void Function(_JsonDiagnosticsNode))>; + /// Defines diagnostics data for a [value]. /// /// For debug and profile modes, [DiagnosticsNode] provides a high quality @@ -1605,29 +1617,12 @@ abstract class DiagnosticsNode { /// by this method and interactive tree views in the Flutter IntelliJ /// plugin. @mustCallSuper - Map toJsonMap( - DiagnosticsSerializationDelegate delegate, { - bool fullDetails = true, - }) { + Map toJsonMap(DiagnosticsSerializationDelegate delegate) { Map result = {}; assert(() { final bool hasChildren = getChildren().isNotEmpty; - final Map essentialDetails = { + result = { 'description': toDescription(), - 'shouldIndent': style != DiagnosticsTreeStyle.flat && - style != DiagnosticsTreeStyle.error, - ...delegate.additionalNodeProperties(this, fullDetails: fullDetails), - if (delegate.subtreeDepth > 0) - 'children': toJsonList( - delegate.filterChildren(getChildren(), this), - this, - delegate, - fullDetails: fullDetails, - ), - }; - - result = !fullDetails ? essentialDetails : { - ...essentialDetails, 'type': runtimeType.toString(), if (name != null) 'name': name, @@ -1651,12 +1646,18 @@ abstract class DiagnosticsNode { 'allowWrap': allowWrap, if (allowNameWrap) 'allowNameWrap': allowNameWrap, + ...delegate.additionalNodeProperties(this), if (delegate.includeProperties) 'properties': toJsonList( delegate.filterProperties(getProperties(), this), this, delegate, - fullDetails: fullDetails, + ), + if (delegate.subtreeDepth > 0) + 'children': toJsonList( + delegate.filterChildren(getChildren(), this), + this, + delegate, ), }; return true; @@ -1664,6 +1665,35 @@ abstract class DiagnosticsNode { return result; } + /// Iteratively serialize the node to a JSON map according to the + /// configuration provided in the [DiagnosticsSerializationDelegate]. + /// + /// This is only used when [WidgetInspectorServiceExtensions.getRootWidgetTree] + /// is called with fullDetails=false. To get the full widget details, including + /// any details provided by subclasses, [toJsonMap] should be used instead. + /// + /// See https://github.com/flutter/devtools/issues/8553 for details about this + /// iterative approach. + Map toJsonMapIterative( + DiagnosticsSerializationDelegate delegate, + ) { + final _NodesToJsonifyStack childrenToJsonify = + ListQueue<(DiagnosticsNode, void Function(_JsonDiagnosticsNode))>(); + _JsonDiagnosticsNode result = {}; + assert(() { + result = _toJson( + delegate, + childrenToJsonify: childrenToJsonify, + ); + _jsonifyNextNodesInStack( + childrenToJsonify, + delegate: delegate, + ); + return true; + }()); + return result; + } + /// Serializes a [List] of [DiagnosticsNode]s to a JSON list according to /// the configuration provided by the [DiagnosticsSerializationDelegate]. /// @@ -1672,9 +1702,8 @@ abstract class DiagnosticsNode { static List> toJsonList( List? nodes, DiagnosticsNode? parent, - DiagnosticsSerializationDelegate delegate, { - bool fullDetails = true, - }) { + DiagnosticsSerializationDelegate delegate, + ) { bool truncated = false; if (nodes == null) { return const >[]; @@ -1685,11 +1714,9 @@ abstract class DiagnosticsNode { nodes.add(DiagnosticsNode.message('...')); truncated = true; } - final List> json = nodes.map>((DiagnosticsNode node) { - return node.toJsonMap( - delegate.delegateForNode(node), - fullDetails: fullDetails, - ); + final List<_JsonDiagnosticsNode> json = + nodes.map<_JsonDiagnosticsNode>((DiagnosticsNode node) { + return node.toJsonMap(delegate.delegateForNode(node)); }).toList(); if (truncated) { json.last['truncated'] = true; @@ -1803,6 +1830,74 @@ abstract class DiagnosticsNode { }()); return result; } + + void _jsonifyNextNodesInStack( + _NodesToJsonifyStack toJsonify, { + required DiagnosticsSerializationDelegate delegate, + }) { + while (toJsonify.isNotEmpty) { + final ( + DiagnosticsNode nextNode, + void Function(_JsonDiagnosticsNode) callback + ) = toJsonify.removeFirst(); + final _JsonDiagnosticsNode nodeAsJson = nextNode._toJson( + delegate, + childrenToJsonify: toJsonify, + ); + callback(nodeAsJson); + } + } + + Map _toJson( + DiagnosticsSerializationDelegate delegate, { + required _NodesToJsonifyStack childrenToJsonify, + }) { + final List<_JsonDiagnosticsNode> childrenJsonList = + <_JsonDiagnosticsNode>[]; + final bool includeChildren = + getChildren().isNotEmpty && delegate.subtreeDepth > 0; + + // Collect the children nodes to convert to JSON later. + bool truncated = false; + if (includeChildren) { + List childrenNodes = + delegate.filterChildren(getChildren(), this); + final int originalNodeCount = childrenNodes.length; + childrenNodes = delegate.truncateNodesList(childrenNodes, this); + if (childrenNodes.length != originalNodeCount) { + childrenNodes.add(DiagnosticsNode.message('...')); + truncated = true; + } + for (final DiagnosticsNode child in childrenNodes) { + childrenToJsonify.add(( + child, + (_JsonDiagnosticsNode jsonChild) { + childrenJsonList.add(jsonChild); + } + )); + } + } + + final String description = toDescription(); + final String widgetRuntimeType = + description == '[root]' ? 'RootWidget' : description.split('-').first; + final bool shouldIndent = style != DiagnosticsTreeStyle.flat && + style != DiagnosticsTreeStyle.error; + + return { + 'description': description, + 'shouldIndent': shouldIndent, + // TODO(elliette): This can be removed to reduce the JSON response even + // further once DevTools computes the widget runtime type from the + // description instead, see: + // https://github.com/flutter/devtools/issues/8556 + 'widgetRuntimeType': widgetRuntimeType, + if (truncated) + 'truncated': truncated, + ...delegate.additionalNodeProperties(this, fullDetails: false), + if (includeChildren) 'children': childrenJsonList, + }; + } } /// Debugging message displayed like a property. @@ -1872,17 +1967,8 @@ class StringProperty extends DiagnosticsProperty { final bool quoted; @override - Map toJsonMap( - DiagnosticsSerializationDelegate delegate, { - bool fullDetails = true, - }) { - final Map json = super.toJsonMap( - delegate, - fullDetails: fullDetails, - ); - if (!fullDetails) { - return json; - } + Map toJsonMap(DiagnosticsSerializationDelegate delegate) { + final Map json = super.toJsonMap(delegate); json['quoted'] = quoted; return json; } @@ -1937,18 +2023,8 @@ abstract class _NumProperty extends DiagnosticsProperty { }) : super.lazy(); @override - Map toJsonMap( - DiagnosticsSerializationDelegate delegate, { - bool fullDetails = true, - }) { - final Map json = super.toJsonMap( - delegate, - fullDetails: fullDetails, - ); - if (!fullDetails) { - return json; - } - + Map toJsonMap(DiagnosticsSerializationDelegate delegate) { + final Map json = super.toJsonMap(delegate); if (unit != null) { json['unit'] = unit; } @@ -2131,17 +2207,8 @@ class FlagProperty extends DiagnosticsProperty { ); @override - Map toJsonMap( - DiagnosticsSerializationDelegate delegate, { - bool fullDetails = true, - }) { - final Map json = super.toJsonMap( - delegate, - fullDetails: fullDetails, - ); - if (!fullDetails) { - return json; - } + Map toJsonMap(DiagnosticsSerializationDelegate delegate) { + final Map json = super.toJsonMap(delegate); if (ifTrue != null) { json['ifTrue'] = ifTrue; } @@ -2262,17 +2329,8 @@ class IterableProperty extends DiagnosticsProperty> { } @override - Map toJsonMap( - DiagnosticsSerializationDelegate delegate, { - bool fullDetails = true, - }) { - final Map json = super.toJsonMap( - delegate, - fullDetails: fullDetails, - ); - if (!fullDetails) { - return json; - } + Map toJsonMap(DiagnosticsSerializationDelegate delegate) { + final Map json = super.toJsonMap(delegate); if (value != null) { json['values'] = value!.map((T value) => value.toString()).toList(); } @@ -2409,17 +2467,8 @@ class ObjectFlagProperty extends DiagnosticsProperty { } @override - Map toJsonMap( - DiagnosticsSerializationDelegate delegate, { - bool fullDetails = true, - }) { - final Map json = super.toJsonMap( - delegate, - fullDetails: fullDetails, - ); - if (!fullDetails) { - return json; - } + Map toJsonMap(DiagnosticsSerializationDelegate delegate) { + final Map json = super.toJsonMap(delegate); if (ifPresent != null) { json['ifPresent'] = ifPresent; } @@ -2496,17 +2545,8 @@ class FlagsSummary extends DiagnosticsProperty> { } @override - Map toJsonMap( - DiagnosticsSerializationDelegate delegate, { - bool fullDetails = true, - }) { - final Map json = super.toJsonMap( - delegate, - fullDetails: fullDetails, - ); - if (!fullDetails) { - return json; - } + Map toJsonMap(DiagnosticsSerializationDelegate delegate) { + final Map json = super.toJsonMap(delegate); if (value.isNotEmpty) { json['values'] = _formattedValues().toList(); } @@ -2625,10 +2665,7 @@ class DiagnosticsProperty extends DiagnosticsNode { final bool allowNameWrap; @override - Map toJsonMap( - DiagnosticsSerializationDelegate delegate, { - bool fullDetails = true, - }) { + Map toJsonMap(DiagnosticsSerializationDelegate delegate) { final T? v = value; List>? properties; if (delegate.expandPropertyValues && delegate.includeProperties && v is Diagnosticable && getProperties().isEmpty) { @@ -2638,16 +2675,9 @@ class DiagnosticsProperty extends DiagnosticsNode { delegate.filterProperties(v.toDiagnosticsNode().getProperties(), this), this, delegate, - fullDetails: fullDetails, ); } - final Map json = super.toJsonMap( - delegate, - fullDetails: fullDetails, - ); - if (!fullDetails) { - return json; - } + final Map json = super.toJsonMap(delegate); if (properties != null) { json['properties'] = properties; } diff --git a/packages/flutter/lib/src/foundation/observer_list.dart b/packages/flutter/lib/src/foundation/observer_list.dart index 27878026ee3..d1bae685467 100644 --- a/packages/flutter/lib/src/foundation/observer_list.dart +++ b/packages/flutter/lib/src/foundation/observer_list.dart @@ -43,12 +43,15 @@ class ObserverList extends Iterable { /// /// Returns whether the item was present in the list. bool remove(T item) { - _isDirty = true; - _set.clear(); // Clear the set so that we don't leak items. - return _list.remove(item); + final bool removed = _list.remove(item); + if (removed) { + _isDirty = true; + _set.clear(); // Clear the set so that we don't leak items. + } + return removed; } - /// Removes all items from the list. + /// Removes all items from the [ObserverList]. void clear() { _isDirty = false; _list.clear(); @@ -78,6 +81,10 @@ class ObserverList extends Iterable { @override bool get isNotEmpty => _list.isNotEmpty; + /// Creates a List containing the elements of the [ObserverList]. + /// + /// Overrides the default implementation of the [Iterable] to reduce number + /// of allocations. @override List toList({bool growable = true}) { return _list.toList(growable: growable); @@ -126,6 +133,9 @@ class HashedObserverList extends Iterable { return true; } + /// Removes all items from the [HashedObserverList]. + void clear() => _map.clear(); + @override bool contains(Object? element) => _map.containsKey(element); @@ -137,4 +147,18 @@ class HashedObserverList extends Iterable { @override bool get isNotEmpty => _map.isNotEmpty; + + /// Creates a List containing the elements of the [HashedObserverList]. + /// + /// Overrides the default implementation of [Iterable] to reduce number of + /// allocations. + @override + List toList({bool growable = true}) { + final Iterator iterator = _map.keys.iterator; + return List.generate( + _map.length, + (_) => (iterator..moveNext()).current, + growable: growable, + ); + } } diff --git a/packages/flutter/lib/src/material/action_chip.dart b/packages/flutter/lib/src/material/action_chip.dart index 5d58e0a3eba..f13f25dce6d 100644 --- a/packages/flutter/lib/src/material/action_chip.dart +++ b/packages/flutter/lib/src/material/action_chip.dart @@ -120,6 +120,7 @@ class ActionChip extends StatelessWidget implements ChipAttributes, TappableChip this.iconTheme, this.avatarBoxConstraints, this.chipAnimationStyle, + this.mouseCursor, }) : assert(pressElevation == null || pressElevation >= 0.0), assert(elevation == null || elevation >= 0.0), _chipVariant = _ChipVariant.flat; @@ -156,6 +157,7 @@ class ActionChip extends StatelessWidget implements ChipAttributes, TappableChip this.iconTheme, this.avatarBoxConstraints, this.chipAnimationStyle, + this.mouseCursor, }) : assert(pressElevation == null || pressElevation >= 0.0), assert(elevation == null || elevation >= 0.0), _chipVariant = _ChipVariant.elevated; @@ -208,6 +210,8 @@ class ActionChip extends StatelessWidget implements ChipAttributes, TappableChip final BoxConstraints? avatarBoxConstraints; @override final ChipAnimationStyle? chipAnimationStyle; + @override + final MouseCursor? mouseCursor; @override bool get isEnabled => onPressed != null; @@ -247,6 +251,7 @@ class ActionChip extends StatelessWidget implements ChipAttributes, TappableChip iconTheme: iconTheme, avatarBoxConstraints: avatarBoxConstraints, chipAnimationStyle: chipAnimationStyle, + mouseCursor: mouseCursor, ); } } diff --git a/packages/flutter/lib/src/material/app.dart b/packages/flutter/lib/src/material/app.dart index 3b871d56a26..b8695a54095 100644 --- a/packages/flutter/lib/src/material/app.dart +++ b/packages/flutter/lib/src/material/app.dart @@ -22,6 +22,7 @@ import 'package:flutter/services.dart'; import 'arc.dart'; import 'colors.dart'; import 'floating_action_button.dart'; +import 'icon_button.dart'; import 'icons.dart'; import 'material_localizations.dart'; import 'page.dart'; @@ -904,6 +905,9 @@ class MaterialScrollBehavior extends ScrollBehavior { } class _MaterialAppState extends State { + static const double _moveExitWidgetSelectionIconSize = 32; + static const double _moveExitWidgetSelectionTargetSize = 40; + late HeroController _heroController; bool get _usesRouter => widget.routerDelegate != null || widget.routerConfig != null; @@ -934,14 +938,65 @@ class _MaterialAppState extends State { ]; } - Widget _inspectorSelectButtonBuilder(BuildContext context, VoidCallback onPressed) { + Widget _exitWidgetSelectionButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + required GlobalKey key, + }) { return FloatingActionButton( + key: key, onPressed: onPressed, mini: true, - child: const Icon(Icons.search), + backgroundColor: _widgetSelectionButtonsBackgroundColor(context), + foregroundColor: _widgetSelectionButtonsForegroundColor(context), + child: const Icon( + Icons.close, + semanticLabel: 'Exit Select Widget mode.', + ), ); } + Widget _moveExitWidgetSelectionButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + bool isLeftAligned = true, + }) { + return IconButton( + color: _widgetSelectionButtonsBackgroundColor(context), + padding: EdgeInsets.zero, + iconSize: _moveExitWidgetSelectionIconSize, + onPressed: onPressed, + constraints: const BoxConstraints( + minWidth: _moveExitWidgetSelectionTargetSize, + minHeight: _moveExitWidgetSelectionTargetSize, + ), + icon: Icon( + isLeftAligned ? Icons.arrow_right : Icons.arrow_left, + semanticLabel: + 'Move "Exit Select Widget mode" button to the ${isLeftAligned ? 'right' : 'left'}.', + )); + } + + Color _widgetSelectionButtonsForegroundColor(BuildContext context) { + final ThemeData theme = Theme.of(context); + return _isDarkTheme(context) + ? theme.colorScheme.onPrimaryContainer + : theme.colorScheme.primaryContainer; + } + + Color _widgetSelectionButtonsBackgroundColor(BuildContext context) { + final ThemeData theme = Theme.of(context); + return _isDarkTheme(context) + ? theme.colorScheme.primaryContainer + : theme.colorScheme.onPrimaryContainer; + } + + bool _isDarkTheme(BuildContext context) { + return widget.themeMode == ThemeMode.dark || + widget.themeMode == ThemeMode.system && + MediaQuery.platformBrightnessOf(context) == Brightness.dark; + } + ThemeData _themeBuilder(BuildContext context) { ThemeData? theme; // Resolve which theme to use based on brightness and high contrast. @@ -1044,7 +1099,9 @@ class _MaterialAppState extends State { showPerformanceOverlay: widget.showPerformanceOverlay, showSemanticsDebugger: widget.showSemanticsDebugger, debugShowCheckedModeBanner: widget.debugShowCheckedModeBanner, - inspectorSelectButtonBuilder: _inspectorSelectButtonBuilder, + exitWidgetSelectionButtonBuilder: _exitWidgetSelectionButtonBuilder, + moveExitWidgetSelectionButtonBuilder: + _moveExitWidgetSelectionButtonBuilder, shortcuts: widget.shortcuts, actions: widget.actions, restorationScopeId: widget.restorationScopeId, @@ -1078,7 +1135,9 @@ class _MaterialAppState extends State { showPerformanceOverlay: widget.showPerformanceOverlay, showSemanticsDebugger: widget.showSemanticsDebugger, debugShowCheckedModeBanner: widget.debugShowCheckedModeBanner, - inspectorSelectButtonBuilder: _inspectorSelectButtonBuilder, + exitWidgetSelectionButtonBuilder: _exitWidgetSelectionButtonBuilder, + moveExitWidgetSelectionButtonBuilder: + _moveExitWidgetSelectionButtonBuilder, shortcuts: widget.shortcuts, actions: widget.actions, restorationScopeId: widget.restorationScopeId, diff --git a/packages/flutter/lib/src/material/bottom_sheet.dart b/packages/flutter/lib/src/material/bottom_sheet.dart index 9dfeec84cfb..d25883e58b5 100644 --- a/packages/flutter/lib/src/material/bottom_sheet.dart +++ b/packages/flutter/lib/src/material/bottom_sheet.dart @@ -15,17 +15,16 @@ import 'bottom_sheet_theme.dart'; import 'color_scheme.dart'; import 'colors.dart'; import 'constants.dart'; -import 'curves.dart'; import 'debug.dart'; import 'material.dart'; import 'material_localizations.dart'; -import 'material_state.dart'; +import 'motion.dart'; import 'scaffold.dart'; import 'theme.dart'; const Duration _bottomSheetEnterDuration = Duration(milliseconds: 250); const Duration _bottomSheetExitDuration = Duration(milliseconds: 200); -const Curve _modalBottomSheetCurve = decelerateEasing; +const Curve _modalBottomSheetCurve = Easing.legacyDecelerate; const double _minFlingVelocity = 700.0; const double _closeProgressThreshold = 0.5; const double _defaultScrollControlDisabledMaxHeightRatio = 9.0 / 16.0; @@ -266,11 +265,11 @@ class _BottomSheetState extends State { bool get _dismissUnderway => widget.animationController!.status == AnimationStatus.reverse; - Set dragHandleMaterialState = {}; + Set dragHandleStates = {}; void _handleDragStart(DragStartDetails details) { setState(() { - dragHandleMaterialState.add(MaterialState.dragged); + dragHandleStates.add(WidgetState.dragged); }); widget.onDragStart?.call(details); } @@ -297,7 +296,7 @@ class _BottomSheetState extends State { return; } setState(() { - dragHandleMaterialState.remove(MaterialState.dragged); + dragHandleStates.remove(WidgetState.dragged); }); bool isClosing = false; if (details.velocity.pixelsPerSecond.dy > _minFlingVelocity) { @@ -335,12 +334,12 @@ class _BottomSheetState extends State { } void _handleDragHandleHover(bool hovering) { - if (hovering != dragHandleMaterialState.contains(MaterialState.hovered)) { + if (hovering != dragHandleStates.contains(WidgetState.hovered)) { setState(() { if (hovering){ - dragHandleMaterialState.add(MaterialState.hovered); + dragHandleStates.add(WidgetState.hovered); } else { - dragHandleMaterialState.remove(MaterialState.hovered); + dragHandleStates.remove(WidgetState.hovered); } }); } @@ -361,11 +360,11 @@ class _BottomSheetState extends State { final bool showDragHandle = widget.showDragHandle ?? (widget.enableDrag && (bottomSheetTheme.showDragHandle ?? false)); Widget? dragHandle; - if (showDragHandle){ + if (showDragHandle) { dragHandle = _DragHandle( onSemanticsTap: widget.onClosing, handleHover: _handleDragHandleHover, - materialState: dragHandleMaterialState, + states: dragHandleStates, dragHandleColor: widget.dragHandleColor, dragHandleSize: widget.dragHandleSize, ); @@ -431,20 +430,18 @@ class _BottomSheetState extends State { // See scaffold.dart -typedef _SizeChangeCallback = void Function(Size size); - class _DragHandle extends StatelessWidget { const _DragHandle({ required this.onSemanticsTap, required this.handleHover, - required this.materialState, + required this.states, this.dragHandleColor, this.dragHandleSize, }); final VoidCallback? onSemanticsTap; final ValueChanged handleHover; - final Set materialState; + final Set states; final Color? dragHandleColor; final Size? dragHandleSize; @@ -470,8 +467,8 @@ class _DragHandle extends StatelessWidget { width: handleSize.width, decoration: BoxDecoration( borderRadius: BorderRadius.circular(handleSize.height/2), - color: MaterialStateProperty.resolveAs(dragHandleColor, materialState) - ?? MaterialStateProperty.resolveAs(bottomSheetTheme.dragHandleColor, materialState) + color: WidgetStateProperty.resolveAs(dragHandleColor, states) + ?? WidgetStateProperty.resolveAs(bottomSheetTheme.dragHandleColor, states) ?? m3Defaults.dragHandleColor, ), ), @@ -491,7 +488,7 @@ class _BottomSheetLayoutWithSizeListener extends SingleChildRenderObjectWidget { super.child, }); - final _SizeChangeCallback onChildSizeChanged; + final ValueChanged onChildSizeChanged; final double animationValue; final bool isScrollControlled; final double scrollControlDisabledMaxHeightRatio; @@ -518,7 +515,7 @@ class _BottomSheetLayoutWithSizeListener extends SingleChildRenderObjectWidget { class _RenderBottomSheetLayoutWithSizeListener extends RenderShiftedBox { _RenderBottomSheetLayoutWithSizeListener({ RenderBox? child, - required _SizeChangeCallback onChildSizeChanged, + required ValueChanged onChildSizeChanged, required double animationValue, required bool isScrollControlled, required double scrollControlDisabledMaxHeightRatio, @@ -530,9 +527,9 @@ class _RenderBottomSheetLayoutWithSizeListener extends RenderShiftedBox { Size _lastSize = Size.zero; - _SizeChangeCallback get onChildSizeChanged => _onChildSizeChanged; - _SizeChangeCallback _onChildSizeChanged; - set onChildSizeChanged(_SizeChangeCallback newCallback) { + ValueChanged get onChildSizeChanged => _onChildSizeChanged; + ValueChanged _onChildSizeChanged; + set onChildSizeChanged(ValueChanged newCallback) { if (_onChildSizeChanged == newCallback) { return; } @@ -574,50 +571,20 @@ class _RenderBottomSheetLayoutWithSizeListener extends RenderShiftedBox { markNeedsLayout(); } - Size _getSize(BoxConstraints constraints) { - return constraints.constrain(constraints.biggest); - } + @override + double computeMinIntrinsicWidth(double height) => 0.0; @override - double computeMinIntrinsicWidth(double height) { - final double width = _getSize(BoxConstraints.tightForFinite(height: height)).width; - if (width.isFinite) { - return width; - } - return 0.0; - } + double computeMaxIntrinsicWidth(double height) => 0.0; @override - double computeMaxIntrinsicWidth(double height) { - final double width = _getSize(BoxConstraints.tightForFinite(height: height)).width; - if (width.isFinite) { - return width; - } - return 0.0; - } + double computeMinIntrinsicHeight(double width) => 0.0; @override - double computeMinIntrinsicHeight(double width) { - final double height = _getSize(BoxConstraints.tightForFinite(width: width)).height; - if (height.isFinite) { - return height; - } - return 0.0; - } + double computeMaxIntrinsicHeight(double width) => 0.0; @override - double computeMaxIntrinsicHeight(double width) { - final double height = _getSize(BoxConstraints.tightForFinite(width: width)).height; - if (height.isFinite) { - return height; - } - return 0.0; - } - - @override - Size computeDryLayout(BoxConstraints constraints) { - return _getSize(constraints); - } + Size computeDryLayout(BoxConstraints constraints) => constraints.biggest; @override double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { @@ -631,7 +598,7 @@ class _RenderBottomSheetLayoutWithSizeListener extends RenderShiftedBox { return null; } final Size childSize = childConstraints.isTight ? childConstraints.smallest : child.getDryLayout(childConstraints); - return result + _getPositionForChild(_getSize(constraints), childSize).dy; + return result + _getPositionForChild(constraints.biggest, childSize).dy; } BoxConstraints _getConstraintsForChild(BoxConstraints constraints) { @@ -650,7 +617,7 @@ class _RenderBottomSheetLayoutWithSizeListener extends RenderShiftedBox { @override void performLayout() { - size = _getSize(constraints); + size = constraints.biggest; final RenderBox? child = this.child; if (child == null) { return; @@ -1069,10 +1036,15 @@ class ModalBottomSheetRoute extends PopupRoute { } @override - Duration get transitionDuration => _bottomSheetEnterDuration; + Duration get transitionDuration => transitionAnimationController?.duration + ?? sheetAnimationStyle?.duration + ?? _bottomSheetEnterDuration; @override - Duration get reverseTransitionDuration => _bottomSheetExitDuration; + Duration get reverseTransitionDuration => transitionAnimationController?.reverseDuration + ?? transitionAnimationController?.duration + ?? sheetAnimationStyle?.reverseDuration + ?? _bottomSheetExitDuration; @override bool get barrierDismissible => isDismissible; @@ -1137,11 +1109,11 @@ class ModalBottomSheetRoute extends PopupRoute { @override Widget buildModalBarrier() { - if (barrierColor.alpha != 0 && !offstage) { // changedInternalState is called if barrierColor or offstage updates - assert(barrierColor != barrierColor.withOpacity(0.0)); + if (barrierColor.a != 0 && !offstage) { // changedInternalState is called if barrierColor or offstage updates + assert(barrierColor != barrierColor.withValues(alpha: 0.0)); final Animation color = animation!.drive( ColorTween( - begin: barrierColor.withOpacity(0.0), + begin: barrierColor.withValues(alpha: 0.0), end: barrierColor, // changedInternalState is called if barrierColor updates ).chain(CurveTween(curve: barrierCurve)), // changedInternalState is called if barrierCurve updates ); diff --git a/packages/flutter/lib/src/material/button_style.dart b/packages/flutter/lib/src/material/button_style.dart index a61a4e69942..487fd517abf 100644 --- a/packages/flutter/lib/src/material/button_style.dart +++ b/packages/flutter/lib/src/material/button_style.dart @@ -23,6 +23,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; +import 'button_style_button.dart'; import 'ink_well.dart'; import 'material_state.dart'; import 'theme_data.dart'; @@ -174,6 +175,7 @@ class ButtonStyle with Diagnosticable { this.maximumSize, this.iconColor, this.iconSize, + this.iconAlignment, this.side, this.shape, this.mouseCursor, @@ -279,6 +281,22 @@ class ButtonStyle with Diagnosticable { /// The icon's size inside of the button. final MaterialStateProperty? iconSize; + /// The alignment of the button's icon. + /// + /// This property is supported for the following button types: + /// + /// * [ElevatedButton.icon]. + /// * [FilledButton.icon]. + /// * [FilledButton.tonalIcon]. + /// * [OutlinedButton.icon]. + /// * [TextButton.icon]. + /// + /// See also: + /// + /// * [IconAlignment], for more information about the different icon + /// alignments. + final IconAlignment? iconAlignment; + /// The color and weight of the button's outline. /// /// This value is combined with [shape] to create a shape decorated @@ -407,6 +425,7 @@ class ButtonStyle with Diagnosticable { MaterialStateProperty? maximumSize, MaterialStateProperty? iconColor, MaterialStateProperty? iconSize, + IconAlignment? iconAlignment, MaterialStateProperty? side, MaterialStateProperty? shape, MaterialStateProperty? mouseCursor, @@ -433,6 +452,7 @@ class ButtonStyle with Diagnosticable { maximumSize: maximumSize ?? this.maximumSize, iconColor: iconColor ?? this.iconColor, iconSize: iconSize ?? this.iconSize, + iconAlignment: iconAlignment ?? this.iconAlignment, side: side ?? this.side, shape: shape ?? this.shape, mouseCursor: mouseCursor ?? this.mouseCursor, @@ -470,6 +490,7 @@ class ButtonStyle with Diagnosticable { maximumSize: maximumSize ?? style.maximumSize, iconColor: iconColor ?? style.iconColor, iconSize: iconSize ?? style.iconSize, + iconAlignment: iconAlignment ?? style.iconAlignment, side: side ?? style.side, shape: shape ?? style.shape, mouseCursor: mouseCursor ?? style.mouseCursor, @@ -500,6 +521,7 @@ class ButtonStyle with Diagnosticable { maximumSize, iconColor, iconSize, + iconAlignment, side, shape, mouseCursor, @@ -537,6 +559,7 @@ class ButtonStyle with Diagnosticable { && other.maximumSize == maximumSize && other.iconColor == iconColor && other.iconSize == iconSize + && other.iconAlignment == iconAlignment && other.side == side && other.shape == shape && other.mouseCursor == mouseCursor @@ -566,6 +589,7 @@ class ButtonStyle with Diagnosticable { properties.add(DiagnosticsProperty>('maximumSize', maximumSize, defaultValue: null)); properties.add(DiagnosticsProperty>('iconColor', iconColor, defaultValue: null)); properties.add(DiagnosticsProperty>('iconSize', iconSize, defaultValue: null)); + properties.add(EnumProperty('iconAlignment', iconAlignment, defaultValue: null)); properties.add(DiagnosticsProperty>('side', side, defaultValue: null)); properties.add(DiagnosticsProperty>('shape', shape, defaultValue: null)); properties.add(DiagnosticsProperty>('mouseCursor', mouseCursor, defaultValue: null)); @@ -597,6 +621,7 @@ class ButtonStyle with Diagnosticable { maximumSize: MaterialStateProperty.lerp(a?.maximumSize, b?.maximumSize, t, Size.lerp), iconColor: MaterialStateProperty.lerp(a?.iconColor, b?.iconColor, t, Color.lerp), iconSize: MaterialStateProperty.lerp(a?.iconSize, b?.iconSize, t, lerpDouble), + iconAlignment: t < 0.5 ? a?.iconAlignment : b?.iconAlignment, side: _lerpSides(a?.side, b?.side, t), shape: MaterialStateProperty.lerp(a?.shape, b?.shape, t, OutlinedBorder.lerp), mouseCursor: t < 0.5 ? a?.mouseCursor : b?.mouseCursor, diff --git a/packages/flutter/lib/src/material/button_style_button.dart b/packages/flutter/lib/src/material/button_style_button.dart index 74cf34c3f69..a386d79a1e7 100644 --- a/packages/flutter/lib/src/material/button_style_button.dart +++ b/packages/flutter/lib/src/material/button_style_button.dart @@ -86,7 +86,7 @@ abstract class ButtonStyleButton extends StatefulWidget { required this.clipBehavior, this.statesController, this.isSemanticButton = true, - this.iconAlignment = IconAlignment.start, + this.iconAlignment, this.tooltip, required this.child, }); @@ -158,7 +158,7 @@ abstract class ButtonStyleButton extends StatefulWidget { final bool? isSemanticButton; /// {@macro flutter.material.ButtonStyleButton.iconAlignment} - final IconAlignment iconAlignment; + final IconAlignment? iconAlignment; /// Text that describes the action that will occur when the button is pressed or /// hovered over. @@ -407,7 +407,7 @@ class _ButtonStyleState extends State with TickerProviderStat final VisualDensity? resolvedVisualDensity = effectiveValue((ButtonStyle? style) => style?.visualDensity); final MaterialTapTargetSize? resolvedTapTargetSize = effectiveValue((ButtonStyle? style) => style?.tapTargetSize); final Duration? resolvedAnimationDuration = effectiveValue((ButtonStyle? style) => style?.animationDuration); - final bool? resolvedEnableFeedback = effectiveValue((ButtonStyle? style) => style?.enableFeedback); + final bool resolvedEnableFeedback = effectiveValue((ButtonStyle? style) => style?.enableFeedback) ?? true; final AlignmentGeometry? resolvedAlignment = effectiveValue((ButtonStyle? style) => style?.alignment); final Offset densityAdjustment = resolvedVisualDensity!.baseSizeAdjustment; final InteractiveInkFeatureFactory? resolvedSplashFactory = effectiveValue((ButtonStyle? style) => style?.splashFactory); diff --git a/packages/flutter/lib/src/material/calendar_date_picker.dart b/packages/flutter/lib/src/material/calendar_date_picker.dart index 6c96ec343ee..0d471c17ffd 100644 --- a/packages/flutter/lib/src/material/calendar_date_picker.dart +++ b/packages/flutter/lib/src/material/calendar_date_picker.dart @@ -20,6 +20,7 @@ import 'debug.dart'; import 'divider.dart'; import 'icon_button.dart'; import 'icons.dart'; +import 'ink_decoration.dart'; import 'ink_well.dart'; import 'material_localizations.dart'; import 'material_state.dart'; @@ -43,7 +44,7 @@ const double _subHeaderHeight = 52.0; const double _monthNavButtonsWidth = 108.0; // 3.0 is the maximum scale factor on mobile phones. As of 07/30/24, iOS goes up -// to a max of 3.0 text sxale factor, and Android goes up to 2.0. This is the +// to a max of 3.0 text scale factor, and Android goes up to 2.0. This is the // default used for non-range date pickers. This default is changed to a lower // value at different parts of the date pickers depending on content, and device // orientation. @@ -1056,7 +1057,7 @@ class _Day extends StatefulWidget { final bool isSelectedDay; final bool isToday; final ValueChanged onChanged; - final FocusNode? focusNode; + final FocusNode focusNode; @override State<_Day> createState() => _DayState(); @@ -1111,7 +1112,7 @@ class _DayState extends State<_Day> { shape: dayShape, ); - Widget dayWidget = DecoratedBox( + Widget dayWidget = Ink( decoration: decoration, child: Center( child: Text(localizations.formatDecimal(widget.day.day), style: dayStyle?.apply(color: dayForegroundColor)), diff --git a/packages/flutter/lib/src/material/chip.dart b/packages/flutter/lib/src/material/chip.dart index 2392098ed62..9f9bf4b63b7 100644 --- a/packages/flutter/lib/src/material/chip.dart +++ b/packages/flutter/lib/src/material/chip.dart @@ -278,6 +278,19 @@ abstract interface class ChipAttributes { /// ** See code in examples/api/lib/material/chip/chip_attributes.chip_animation_style.0.dart ** /// {@end-tool} ChipAnimationStyle? get chipAnimationStyle; + + /// The cursor for a mouse pointer when it enters or is hovering over the + /// widget. + /// + /// If [mouseCursor] is a [WidgetStateMouseCursor], + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: + /// + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. + /// + /// If this property is null, [WidgetStateMouseCursor.clickable] will be used. + MouseCursor? get mouseCursor; } /// An interface for Material Design chips that can be deleted. @@ -704,6 +717,7 @@ class Chip extends StatelessWidget implements ChipAttributes, DeletableChipAttri this.avatarBoxConstraints, this.deleteIconBoxConstraints, this.chipAnimationStyle, + this.mouseCursor, }) : assert(elevation == null || elevation >= 0.0); @override @@ -756,6 +770,8 @@ class Chip extends StatelessWidget implements ChipAttributes, DeletableChipAttri final BoxConstraints? deleteIconBoxConstraints; @override final ChipAnimationStyle? chipAnimationStyle; + @override + final MouseCursor? mouseCursor; @override Widget build(BuildContext context) { @@ -787,6 +803,7 @@ class Chip extends StatelessWidget implements ChipAttributes, DeletableChipAttri avatarBoxConstraints: avatarBoxConstraints, deleteIconBoxConstraints: deleteIconBoxConstraints, chipAnimationStyle: chipAnimationStyle, + mouseCursor: mouseCursor, ); } } @@ -877,6 +894,7 @@ class RawChip extends StatefulWidget this.avatarBoxConstraints, this.deleteIconBoxConstraints, this.chipAnimationStyle, + this.mouseCursor, }) : assert(pressElevation == null || pressElevation >= 0.0), assert(elevation == null || elevation >= 0.0), deleteIcon = deleteIcon ?? _kDefaultDeleteIcon; @@ -962,6 +980,8 @@ class RawChip extends StatefulWidget final BoxConstraints? deleteIconBoxConstraints; @override final ChipAnimationStyle? chipAnimationStyle; + @override + final MouseCursor? mouseCursor; /// If set, this indicates that the chip should be disabled if all of the /// tap callbacks ([onSelected], [onPressed]) are null. @@ -1407,6 +1427,8 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid onTapDown: canTap ? _handleTapDown : null, onTapCancel: canTap ? _handleTapCancel : null, onHover: canTap ? updateMaterialState(MaterialState.hovered) : null, + mouseCursor: widget.mouseCursor, + hoverColor: (widget.color ?? chipTheme.color) == null ? null : Colors.transparent, customBorder: resolvedShape, child: AnimatedBuilder( animation: Listenable.merge([selectController, enableController]), diff --git a/packages/flutter/lib/src/material/choice_chip.dart b/packages/flutter/lib/src/material/choice_chip.dart index c6729d6717d..d756d372971 100644 --- a/packages/flutter/lib/src/material/choice_chip.dart +++ b/packages/flutter/lib/src/material/choice_chip.dart @@ -101,6 +101,7 @@ class ChoiceChip extends StatelessWidget this.avatarBorder = const CircleBorder(), this.avatarBoxConstraints, this.chipAnimationStyle, + this.mouseCursor, }) : assert(pressElevation == null || pressElevation >= 0.0), assert(elevation == null || elevation >= 0.0), _chipVariant = _ChipVariant.flat; @@ -143,6 +144,7 @@ class ChoiceChip extends StatelessWidget this.avatarBorder = const CircleBorder(), this.avatarBoxConstraints, this.chipAnimationStyle, + this.mouseCursor, }) : assert(pressElevation == null || pressElevation >= 0.0), assert(elevation == null || elevation >= 0.0), _chipVariant = _ChipVariant.elevated; @@ -207,6 +209,8 @@ class ChoiceChip extends StatelessWidget final BoxConstraints? avatarBoxConstraints; @override final ChipAnimationStyle? chipAnimationStyle; + @override + final MouseCursor? mouseCursor; @override bool get isEnabled => onSelected != null; @@ -253,6 +257,7 @@ class ChoiceChip extends StatelessWidget iconTheme: iconTheme, avatarBoxConstraints: avatarBoxConstraints, chipAnimationStyle: chipAnimationStyle, + mouseCursor: mouseCursor, ); } } diff --git a/packages/flutter/lib/src/material/data_table.dart b/packages/flutter/lib/src/material/data_table.dart index 06c5430ee0b..a8d773b2ddf 100644 --- a/packages/flutter/lib/src/material/data_table.dart +++ b/packages/flutter/lib/src/material/data_table.dart @@ -42,6 +42,7 @@ class DataColumn { /// Creates the configuration for a column of a [DataTable]. const DataColumn({ required this.label, + this.columnWidth, this.tooltip, this.numeric = false, this.onSort, @@ -67,6 +68,22 @@ class DataColumn { /// The label should not include the sort indicator. final Widget label; + /// How the horizontal extents of this column of the table should be determined. + /// + /// The [FixedColumnWidth] class can be used to specify a specific width in + /// pixels. This is the cheapest way to size a table's columns. + /// + /// The layout performance of the table depends critically on which column + /// sizing algorithms are used here. In particular, [IntrinsicColumnWidth] is + /// quite expensive because it needs to measure each cell in the column to + /// determine the intrinsic size of the column. + /// + /// If this property is `null`, the table applies a default behavior: + /// - If the table has exactly one column identified as the only text column + /// (i.e., all the rest are numeric), that column uses `IntrinsicColumnWidth(flex: 1.0)`. + /// - All other columns use `IntrinsicColumnWidth()`. + final TableColumnWidth? columnWidth; + /// The column heading's tooltip. /// /// This is a longer description of the column heading, for cases @@ -1122,11 +1139,14 @@ class DataTable extends StatelessWidget { start: paddingStart, end: paddingEnd, ); - if (dataColumnIndex == _onlyTextColumn) { + if (column.columnWidth != null) { + tableColumns[displayColumnIndex] = column.columnWidth!; + } else if (dataColumnIndex == _onlyTextColumn) { tableColumns[displayColumnIndex] = const IntrinsicColumnWidth(flex: 1.0); } else { tableColumns[displayColumnIndex] = const IntrinsicColumnWidth(); } + final Set headerStates = { if (column.onSort == null) MaterialState.disabled, diff --git a/packages/flutter/lib/src/material/drawer.dart b/packages/flutter/lib/src/material/drawer.dart index 82f9db2ee89..1df54b93f96 100644 --- a/packages/flutter/lib/src/material/drawer.dart +++ b/packages/flutter/lib/src/material/drawer.dart @@ -468,6 +468,7 @@ class DrawerController extends StatefulWidget { /// /// Typically used by a [Scaffold] to [open] and [close] the drawer. class DrawerControllerState extends State with SingleTickerProviderStateMixin { + @protected @override void initState() { super.initState(); @@ -481,6 +482,7 @@ class DrawerControllerState extends State with SingleTickerPro ..addStatusListener(_animationStatusChanged); } + @protected @override void dispose() { _historyEntry?.remove(); @@ -489,12 +491,14 @@ class DrawerControllerState extends State with SingleTickerPro super.dispose(); } + @protected @override void didChangeDependencies() { super.didChangeDependencies(); _scrimColorTween = _buildScrimColorTween(); } + @protected @override void didUpdateWidget(DrawerController oldWidget) { super.didUpdateWidget(oldWidget); @@ -751,6 +755,7 @@ class DrawerControllerState extends State with SingleTickerPro } } + @protected @override Widget build(BuildContext context) { assert(debugCheckHasMaterialLocalizations(context)); diff --git a/packages/flutter/lib/src/material/dropdown.dart b/packages/flutter/lib/src/material/dropdown.dart index 0cbbf6bec85..d0eda380eeb 100644 --- a/packages/flutter/lib/src/material/dropdown.dart +++ b/packages/flutter/lib/src/material/dropdown.dart @@ -23,7 +23,6 @@ import 'constants.dart'; import 'debug.dart'; import 'icons.dart'; import 'ink_well.dart'; -import 'input_border.dart'; import 'input_decorator.dart'; import 'material.dart'; import 'material_localizations.dart'; @@ -1010,8 +1009,7 @@ class DropdownButton extends StatefulWidget { ), assert(itemHeight == null || itemHeight >= kMinInteractiveDimension), _inputDecoration = null, - _isEmpty = false, - _isFocused = false; + _isEmpty = false; DropdownButton._formField({ super.key, @@ -1044,7 +1042,6 @@ class DropdownButton extends StatefulWidget { this.padding, required InputDecoration inputDecoration, required bool isEmpty, - required bool isFocused, }) : assert(items == null || items.isEmpty || value == null || items.where((DropdownMenuItem item) { return item.value == value; @@ -1056,8 +1053,7 @@ class DropdownButton extends StatefulWidget { ), assert(itemHeight == null || itemHeight >= kMinInteractiveDimension), _inputDecoration = inputDecoration, - _isEmpty = isEmpty, - _isFocused = isFocused; + _isEmpty = isEmpty; /// The list of items the user can select. /// @@ -1287,8 +1283,6 @@ class DropdownButton extends StatefulWidget { final bool _isEmpty; - final bool _isFocused; - @override State> createState() => _DropdownButtonState(); } @@ -1300,6 +1294,8 @@ class _DropdownButtonState extends State> with WidgetsBindi FocusNode? _internalNode; FocusNode? get focusNode => widget.focusNode ?? _internalNode; late Map> _actionMap; + bool _isHovering = false; + bool _hasPrimaryFocus = false; // Only used if needed to create _internalNode. FocusNode _createFocusNode() { @@ -1321,16 +1317,26 @@ class _DropdownButtonState extends State> with WidgetsBindi onInvoke: (ButtonActivateIntent intent) => _handleTap(), ), }; + focusNode?.addListener(_handleFocusChanged); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); _removeDropdownRoute(); + focusNode?.removeListener(_handleFocusChanged); _internalNode?.dispose(); super.dispose(); } + void _handleFocusChanged() { + if (_hasPrimaryFocus != focusNode!.hasPrimaryFocus) { + setState(() { + _hasPrimaryFocus = focusNode!.hasPrimaryFocus; + }); + } + } + void _removeDropdownRoute() { _dropdownRoute?._dismiss(); _dropdownRoute = null; @@ -1586,30 +1592,76 @@ class _DropdownButtonState extends State> with WidgetsBindi }, ); + // When an InputDecoration is provided, use it instead of using an InkWell + // that overflows in some cases (such as showing an errorText) and requires + // additional logic to manage clipping properly. + // A filled InputDecoration is able to fill the InputDecorator container + // without overflowing. It also supports blending the hovered color. + // According to the Material specification, the overlay colors should be + // visible only for filled dropdown button, see: + // https://m2.material.io/components/menus#dropdown-menu if (widget._inputDecoration != null) { - result = InputDecorator( - decoration: widget._inputDecoration!, - isEmpty: widget._isEmpty, - isFocused: widget._isFocused, - child: result, + InputDecoration effectiveDecoration = widget._inputDecoration!; + if (_hasPrimaryFocus) { + final Color? focusColor = widget.focusColor ?? effectiveDecoration.focusColor; + // For compatibility, override the fill color when focusColor is set. + if (focusColor != null) { + effectiveDecoration = effectiveDecoration.copyWith(fillColor: focusColor); + } + } + result = Focus( + canRequestFocus: _enabled, + focusNode: focusNode, + autofocus: widget.autofocus, + child: MouseRegion( + onEnter: (PointerEnterEvent event) { + if (!_isHovering) { + setState(() { + _isHovering = true; + }); + } + }, + onExit: (PointerExitEvent event) { + if (_isHovering) { + setState(() { + _isHovering = false; + }); + } + }, + cursor: effectiveMouseCursor, + child: GestureDetector( + onTap: _enabled ? _handleTap : null, + behavior: HitTestBehavior.opaque, + child: InputDecorator( + decoration: effectiveDecoration, + isEmpty: widget._isEmpty, + isFocused: _hasPrimaryFocus, + isHovering: _isHovering, + child: widget.padding == null ? result : Padding(padding: widget.padding!, child: result), + ), + ), + ), + ); + } else { + result = InkWell( + mouseCursor: effectiveMouseCursor, + onTap: _enabled ? _handleTap : null, + canRequestFocus: _enabled, + borderRadius: widget.borderRadius, + focusNode: focusNode, + autofocus: widget.autofocus, + focusColor: widget.focusColor ?? Theme.of(context).focusColor, + enableFeedback: false, + child: widget.padding == null ? result : Padding(padding: widget.padding!, child: result), ); } + final bool childHasButtonSemantic = hintIndex != null || (_selectedIndex != null && widget.selectedItemBuilder == null); return Semantics( button: !childHasButtonSemantic, child: Actions( actions: _actionMap, - child: InkWell( - mouseCursor: effectiveMouseCursor, - onTap: _enabled ? _handleTap : null, - canRequestFocus: _enabled, - borderRadius: widget.borderRadius, - focusNode: focusNode, - autofocus: widget.autofocus, - focusColor: widget.focusColor ?? Theme.of(context).focusColor, - enableFeedback: false, - child: widget.padding == null ? result : Padding(padding: widget.padding!, child: result), - ), + child: result, ), ); } @@ -1679,13 +1731,13 @@ class DropdownButtonFormField extends FormField { 'with the same value', ), assert(itemHeight == null || itemHeight >= kMinInteractiveDimension), - decoration = decoration ?? InputDecoration(focusColor: focusColor), + decoration = decoration ?? const InputDecoration(), super( initialValue: value, autovalidateMode: autovalidateMode ?? AutovalidateMode.disabled, builder: (FormFieldState field) { final _DropdownButtonFormFieldState state = field as _DropdownButtonFormFieldState; - final InputDecoration decorationArg = decoration ?? InputDecoration(focusColor: focusColor); + final InputDecoration decorationArg = decoration ?? const InputDecoration(); final InputDecoration effectiveDecoration = decorationArg.applyDefaults( Theme.of(field.context).inputDecorationTheme, ); @@ -1707,19 +1759,6 @@ class DropdownButtonFormField extends FormField { canRequestFocus: false, skipTraversal: true, child: Builder(builder: (BuildContext context) { - final bool isFocused = Focus.of(context).hasFocus; - late final InputBorder? resolvedBorder = switch (( - enabled: effectiveDecoration.enabled, - focused: isFocused, - error: effectiveDecoration.errorText != null, - )) { - (enabled: _, focused: true, error: true) => effectiveDecoration.focusedErrorBorder, - (enabled: _, focused: _, error: true) => effectiveDecoration.errorBorder, - (enabled: _, focused: true, error: _) => effectiveDecoration.focusedBorder, - (enabled: true, focused: _, error: _) => effectiveDecoration.enabledBorder, - (enabled: false, focused: _, error: _) => effectiveDecoration.border, - }; - return DropdownButtonHideUnderline( child: DropdownButton._formField( items: items, @@ -1745,18 +1784,13 @@ class DropdownButtonFormField extends FormField { menuMaxHeight: menuMaxHeight, enableFeedback: enableFeedback, alignment: alignment, - borderRadius: borderRadius ?? switch (resolvedBorder) { - final OutlineInputBorder border => border.borderRadius, - final UnderlineInputBorder border => border.borderRadius, - _ => null, - }, + borderRadius: borderRadius, // Clear the decoration hintText because DropdownButton has its own hint logic. inputDecoration: effectiveDecoration.copyWith( errorText: field.errorText, hintText: effectiveDecoration.hintText != null ? '' : null, ), isEmpty: isEmpty, - isFocused: isFocused, padding: padding, ), ); diff --git a/packages/flutter/lib/src/material/dropdown_menu.dart b/packages/flutter/lib/src/material/dropdown_menu.dart index 7ae84b4fa03..e078e057a60 100644 --- a/packages/flutter/lib/src/material/dropdown_menu.dart +++ b/packages/flutter/lib/src/material/dropdown_menu.dart @@ -518,6 +518,7 @@ class _DropdownMenuState extends State> { double? leadingPadding; bool _menuHasEnabledItem = false; TextEditingController? _localTextEditingController; + final FocusNode _internalFocudeNode = FocusNode(); TextEditingValue get _initialTextEditingValue { for (final DropdownMenuEntry entry in filteredEntries) { @@ -554,6 +555,7 @@ class _DropdownMenuState extends State> { _localTextEditingController?.dispose(); _localTextEditingController = null; } + _internalFocudeNode.dispose(); super.dispose(); } @@ -832,10 +834,32 @@ class _DropdownMenuState extends State> { _enableFilter = false; } controller.open(); + _internalFocudeNode.requestFocus(); } setState(() {}); } + void _handleEditingComplete() { + if (currentHighlight != null) { + final DropdownMenuEntry entry = filteredEntries[currentHighlight!]; + if (entry.enabled) { + _localTextEditingController?.value = TextEditingValue( + text: entry.label, + selection: TextSelection.collapsed(offset: entry.label.length), + ); + widget.onSelected?.call(entry.value); + } + } else { + if (_controller.isOpen) { + widget.onSelected?.call(null); + } + } + if (!widget.enableSearch) { + currentHighlight = null; + } + _controller.close(); + } + @override Widget build(BuildContext context) { final TextDirection textDirection = Directionality.of(context); @@ -902,7 +926,6 @@ class _DropdownMenuState extends State> { controller: _controller, menuChildren: menu, crossAxisUnconstrained: false, - layerLink: LayerLink(), builder: (BuildContext context, MenuController controller, Widget? child) { assert(_initialMenu != null); final Widget trailingButton = Padding( @@ -935,24 +958,7 @@ class _DropdownMenuState extends State> { textAlignVertical: TextAlignVertical.center, style: effectiveTextStyle, controller: _localTextEditingController, - onEditingComplete: () { - if (currentHighlight != null) { - final DropdownMenuEntry entry = filteredEntries[currentHighlight!]; - if (entry.enabled) { - _localTextEditingController?.value = TextEditingValue( - text: entry.label, - selection: TextSelection.collapsed(offset: entry.label.length), - ); - widget.onSelected?.call(entry.value); - } - } else { - widget.onSelected?.call(null); - } - if (!widget.enableSearch) { - currentHighlight = null; - } - controller.close(); - }, + onEditingComplete: _handleEditingComplete, onTap: !widget.enabled ? null : () { handlePressed(controller); }, @@ -1023,6 +1029,17 @@ class _DropdownMenuState extends State> { ); } + // Wrap the menu anchor with an Align to narrow down the constraints. + // Without this Align, when tight constraints are applied to DropdownMenu, + // the menu will appear below these constraints instead of below the + // text field. + menuAnchor = Align( + alignment: AlignmentDirectional.topStart, + widthFactor: 1.0, + heightFactor: 1.0, + child: menuAnchor, + ); + return Actions( actions: >{ _ArrowUpIntent: CallbackAction<_ArrowUpIntent>( @@ -1031,8 +1048,28 @@ class _DropdownMenuState extends State> { _ArrowDownIntent: CallbackAction<_ArrowDownIntent>( onInvoke: handleDownKeyInvoke, ), + _EnterIntent: CallbackAction<_EnterIntent>( + onInvoke: (_) => _handleEditingComplete(), + ), }, - child: menuAnchor, + child: Stack( + children: [ + // Handling keyboard navigation when the Textfield has no focus. + Shortcuts( + shortcuts: const { + SingleActivator(LogicalKeyboardKey.arrowUp): _ArrowUpIntent(), + SingleActivator(LogicalKeyboardKey.arrowDown): _ArrowDownIntent(), + SingleActivator(LogicalKeyboardKey.enter): _EnterIntent(), + }, + child: Focus( + focusNode: _internalFocudeNode, + skipTraversal: true, + child: const SizedBox.shrink(), + ), + ), + menuAnchor, + ], + ), ); } } @@ -1052,6 +1089,10 @@ class _ArrowDownIntent extends Intent { const _ArrowDownIntent(); } +class _EnterIntent extends Intent { + const _EnterIntent(); +} + class _DropdownMenuBody extends MultiChildRenderObjectWidget { const _DropdownMenuBody({ super.children, diff --git a/packages/flutter/lib/src/material/elevated_button.dart b/packages/flutter/lib/src/material/elevated_button.dart index 699e77035c2..8ac7a5bb276 100644 --- a/packages/flutter/lib/src/material/elevated_button.dart +++ b/packages/flutter/lib/src/material/elevated_button.dart @@ -80,7 +80,6 @@ class ElevatedButton extends ButtonStyleButton { super.clipBehavior, super.statesController, required super.child, - super.iconAlignment, }); /// Create an elevated button from a pair of widgets that serve as the button's @@ -106,7 +105,7 @@ class ElevatedButton extends ButtonStyleButton { MaterialStatesController? statesController, Widget? icon, required Widget label, - IconAlignment iconAlignment = IconAlignment.start, + IconAlignment? iconAlignment, }) { if (icon == null) { return ElevatedButton( @@ -210,6 +209,7 @@ class ElevatedButton extends ButtonStyleButton { Color? surfaceTintColor, Color? iconColor, double? iconSize, + IconAlignment? iconAlignment, Color? disabledIconColor, Color? overlayColor, double? elevation, @@ -265,6 +265,7 @@ class ElevatedButton extends ButtonStyleButton { surfaceTintColor: ButtonStyleButton.allOrNull(surfaceTintColor), iconColor: ButtonStyleButton.defaultColor(iconColor, disabledIconColor), iconSize: ButtonStyleButton.allOrNull(iconSize), + iconAlignment: iconAlignment, elevation: elevationValue, padding: ButtonStyleButton.allOrNull(padding), minimumSize: ButtonStyleButton.allOrNull(minimumSize), @@ -478,7 +479,7 @@ class _ElevatedButtonWithIcon extends ElevatedButton { super.statesController, required Widget icon, required Widget label, - super.iconAlignment, + IconAlignment? iconAlignment, }) : super( autofocus: autofocus ?? false, child: _ElevatedButtonWithIconChild( @@ -525,16 +526,21 @@ class _ElevatedButtonWithIconChild extends StatelessWidget { final Widget label; final Widget icon; final ButtonStyle? buttonStyle; - final IconAlignment iconAlignment; + final IconAlignment? iconAlignment; @override Widget build(BuildContext context) { final double defaultFontSize = buttonStyle?.textStyle?.resolve(const {})?.fontSize ?? 14.0; final double scale = clampDouble(MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0, 1.0, 2.0) - 1.0; final double gap = lerpDouble(8, 4, scale)!; + final ElevatedButtonThemeData elevatedButtonTheme = ElevatedButtonTheme.of(context); + final IconAlignment effectiveIconAlignment = iconAlignment + ?? elevatedButtonTheme.style?.iconAlignment + ?? buttonStyle?.iconAlignment + ?? IconAlignment.start; return Row( mainAxisSize: MainAxisSize.min, - children: iconAlignment == IconAlignment.start + children: effectiveIconAlignment == IconAlignment.start ? [icon, SizedBox(width: gap), Flexible(child: label)] : [Flexible(child: label), SizedBox(width: gap), icon], ); diff --git a/packages/flutter/lib/src/material/filled_button.dart b/packages/flutter/lib/src/material/filled_button.dart index bfb5bbce735..8a167ff564f 100644 --- a/packages/flutter/lib/src/material/filled_button.dart +++ b/packages/flutter/lib/src/material/filled_button.dart @@ -82,7 +82,6 @@ class FilledButton extends ButtonStyleButton { super.clipBehavior = Clip.none, super.statesController, required super.child, - super.iconAlignment, }) : _variant = _FilledButtonVariant.filled; /// Create a filled button from [icon] and [label]. @@ -107,7 +106,7 @@ class FilledButton extends ButtonStyleButton { MaterialStatesController? statesController, Widget? icon, required Widget label, - IconAlignment iconAlignment = IconAlignment.start, + IconAlignment? iconAlignment, }) { if (icon == null) { return FilledButton( @@ -180,7 +179,7 @@ class FilledButton extends ButtonStyleButton { MaterialStatesController? statesController, Widget? icon, required Widget label, - IconAlignment iconAlignment = IconAlignment.start, + IconAlignment? iconAlignment, }) { if (icon == null) { return FilledButton.tonal( @@ -275,6 +274,7 @@ class FilledButton extends ButtonStyleButton { Color? surfaceTintColor, Color? iconColor, double? iconSize, + IconAlignment? iconAlignment, Color? disabledIconColor, Color? overlayColor, double? elevation, @@ -317,6 +317,7 @@ class FilledButton extends ButtonStyleButton { surfaceTintColor: ButtonStyleButton.allOrNull(surfaceTintColor), iconColor: ButtonStyleButton.defaultColor(iconColor, disabledIconColor), iconSize: ButtonStyleButton.allOrNull(iconSize), + iconAlignment: iconAlignment, elevation: ButtonStyleButton.allOrNull(elevation), padding: ButtonStyleButton.allOrNull(padding), minimumSize: ButtonStyleButton.allOrNull(minimumSize), @@ -501,7 +502,7 @@ class _FilledButtonWithIcon extends FilledButton { super.statesController, required Widget icon, required Widget label, - super.iconAlignment, + IconAlignment? iconAlignment, }) : super( autofocus: autofocus ?? false, child: _FilledButtonWithIconChild( @@ -525,7 +526,7 @@ class _FilledButtonWithIcon extends FilledButton { super.statesController, required Widget icon, required Widget label, - required IconAlignment iconAlignment, + IconAlignment? iconAlignment, }) : super.tonal( autofocus: autofocus ?? false, child: _FilledButtonWithIconChild( @@ -572,7 +573,7 @@ class _FilledButtonWithIconChild extends StatelessWidget { final Widget label; final Widget icon; final ButtonStyle? buttonStyle; - final IconAlignment iconAlignment; + final IconAlignment? iconAlignment; @override Widget build(BuildContext context) { @@ -581,9 +582,14 @@ class _FilledButtonWithIconChild extends StatelessWidget { // Adjust the gap based on the text scale factor. Start at 8, and lerp // to 4 based on how large the text is. final double gap = lerpDouble(8, 4, scale)!; + final FilledButtonThemeData filledButtonTheme = FilledButtonTheme.of(context); + final IconAlignment effectiveIconAlignment = iconAlignment + ?? filledButtonTheme.style?.iconAlignment + ?? buttonStyle?.iconAlignment + ?? IconAlignment.start; return Row( mainAxisSize: MainAxisSize.min, - children: iconAlignment == IconAlignment.start + children: effectiveIconAlignment == IconAlignment.start ? [icon, SizedBox(width: gap), Flexible(child: label)] : [Flexible(child: label), SizedBox(width: gap), icon], ); diff --git a/packages/flutter/lib/src/material/filter_chip.dart b/packages/flutter/lib/src/material/filter_chip.dart index 7fa508a64f3..e970c23a8f4 100644 --- a/packages/flutter/lib/src/material/filter_chip.dart +++ b/packages/flutter/lib/src/material/filter_chip.dart @@ -113,6 +113,7 @@ class FilterChip extends StatelessWidget this.avatarBoxConstraints, this.deleteIconBoxConstraints, this.chipAnimationStyle, + this.mouseCursor, }) : assert(pressElevation == null || pressElevation >= 0.0), assert(elevation == null || elevation >= 0.0), _chipVariant = _ChipVariant.flat; @@ -160,6 +161,7 @@ class FilterChip extends StatelessWidget this.avatarBoxConstraints, this.deleteIconBoxConstraints, this.chipAnimationStyle, + this.mouseCursor, }) : assert(pressElevation == null || pressElevation >= 0.0), assert(elevation == null || elevation >= 0.0), _chipVariant = _ChipVariant.elevated; @@ -234,6 +236,8 @@ class FilterChip extends StatelessWidget final BoxConstraints? deleteIconBoxConstraints; @override final ChipAnimationStyle? chipAnimationStyle; + @override + final MouseCursor? mouseCursor; @override bool get isEnabled => onSelected != null; @@ -286,6 +290,7 @@ class FilterChip extends StatelessWidget avatarBoxConstraints: avatarBoxConstraints, deleteIconBoxConstraints: deleteIconBoxConstraints, chipAnimationStyle: chipAnimationStyle, + mouseCursor: mouseCursor, ); } } diff --git a/packages/flutter/lib/src/material/ink_well.dart b/packages/flutter/lib/src/material/ink_well.dart index 4be927cf188..831776bdfb6 100644 --- a/packages/flutter/lib/src/material/ink_well.dart +++ b/packages/flutter/lib/src/material/ink_well.dart @@ -1283,12 +1283,16 @@ class _InkResponseState extends State<_InkResponseStateWidget> assert(widget.debugCheckContext(context)); super.build(context); // See AutomaticKeepAliveClientMixin. - Color getHighlightColorForType(_HighlightType type) { - const Set pressed = {MaterialState.pressed}; - const Set focused = {MaterialState.focused}; - const Set hovered = {MaterialState.hovered}; + final ThemeData theme = Theme.of(context); + const Set highlightableStates = {MaterialState.focused, MaterialState.hovered, MaterialState.pressed}; + final Set nonHighlightableStates = statesController.value.difference(highlightableStates); + // Each highlightable state will be resolved separately to get the corresponding color. + // For this resolution to be correct, the non-highlightable states should be preserved. + final Set pressed = {...nonHighlightableStates, MaterialState.pressed}; + final Set focused = {...nonHighlightableStates, MaterialState.focused}; + final Set hovered = {...nonHighlightableStates, MaterialState.hovered}; - final ThemeData theme = Theme.of(context); + Color getHighlightColorForType(_HighlightType type) { return switch (type) { // The pressed state triggers a ripple (ink splash), per the current // Material Design spec. A separate highlight is no longer used. @@ -1458,7 +1462,7 @@ class InkWell extends InkResponse { super.radius, super.borderRadius, super.customBorder, - bool? enableFeedback = true, + super.enableFeedback, super.excludeFromSemantics, super.focusNode, super.canRequestFocus, @@ -1469,6 +1473,5 @@ class InkWell extends InkResponse { }) : super( containedInkWell: true, highlightShape: BoxShape.rectangle, - enableFeedback: enableFeedback ?? true, ); } diff --git a/packages/flutter/lib/src/material/input_border.dart b/packages/flutter/lib/src/material/input_border.dart index 1817e90abf6..af6508f232d 100644 --- a/packages/flutter/lib/src/material/input_border.dart +++ b/packages/flutter/lib/src/material/input_border.dart @@ -428,7 +428,7 @@ class OutlineInputBorder extends InputBorder { @override bool get preferPaintInterior => true; - Path _gapBorderPath(Canvas canvas, RRect center, double start, double extent) { + Path _gapBorderPath(Canvas canvas, RRect center, double outerWidth, double start, double extent) { // When the corner radii on any side add up to be greater than the // given height, each radius has to be scaled to not exceed the // size of the width/height of the RRect. @@ -476,20 +476,20 @@ class OutlineInputBorder extends InputBorder { // Draw top border from top left corner to gap start. if (start > scaledRRect.tlRadiusX) { - path.lineTo(scaledRRect.left + start, scaledRRect.top); + path.lineTo(start, scaledRRect.top); } // Draw top border from gap end to top right corner and draw top right corner. const double trCornerArcStart = (3 * math.pi) / 2.0; const double trCornerArcSweep = cornerArcSweep; - if (start + extent < scaledRRect.width - scaledRRect.trRadiusX) { - path.moveTo(scaledRRect.left + start + extent, scaledRRect.top); + if (start + extent < outerWidth - scaledRRect.trRadiusX) { + path.moveTo(start + extent, scaledRRect.top); path.lineTo(scaledRRect.right - scaledRRect.trRadiusX, scaledRRect.top); if (scaledRRect.trRadius != Radius.zero) { path.addArc(trCorner, trCornerArcStart, trCornerArcSweep); } - } else if (start + extent < scaledRRect.width) { - final double dx = scaledRRect.width - (start + extent); + } else if (start + extent < outerWidth) { + final double dx = outerWidth - (start + extent); final double sweep = math.asin(clampDouble(1 - dx / scaledRRect.trRadiusX, 0.0, 1.0)); path.addArc(trCorner, trCornerArcStart + sweep, trCornerArcSweep - sweep); } @@ -546,7 +546,7 @@ class OutlineInputBorder extends InputBorder { TextDirection.rtl => gapStart + gapPadding - extent, TextDirection.ltr => gapStart - gapPadding, }; - final Path path = _gapBorderPath(canvas, center, math.max(0.0, start), extent); + final Path path = _gapBorderPath(canvas, center, outer.width, math.max(0.0, start), extent); canvas.drawPath(path, paint); } } diff --git a/packages/flutter/lib/src/material/input_chip.dart b/packages/flutter/lib/src/material/input_chip.dart index 28a819b6aad..a2ac93ed24e 100644 --- a/packages/flutter/lib/src/material/input_chip.dart +++ b/packages/flutter/lib/src/material/input_chip.dart @@ -132,6 +132,7 @@ class InputChip extends StatelessWidget this.avatarBoxConstraints, this.deleteIconBoxConstraints, this.chipAnimationStyle, + this.mouseCursor, }) : assert(pressElevation == null || pressElevation >= 0.0), assert(elevation == null || elevation >= 0.0); @@ -209,6 +210,8 @@ class InputChip extends StatelessWidget final BoxConstraints? deleteIconBoxConstraints; @override final ChipAnimationStyle? chipAnimationStyle; + @override + final MouseCursor? mouseCursor; @override Widget build(BuildContext context) { @@ -257,6 +260,7 @@ class InputChip extends StatelessWidget avatarBoxConstraints: avatarBoxConstraints, deleteIconBoxConstraints: deleteIconBoxConstraints, chipAnimationStyle: chipAnimationStyle, + mouseCursor: mouseCursor, ); } } diff --git a/packages/flutter/lib/src/material/input_decorator.dart b/packages/flutter/lib/src/material/input_decorator.dart index 3309b5c2bed..78cfa0c2162 100644 --- a/packages/flutter/lib/src/material/input_decorator.dart +++ b/packages/flutter/lib/src/material/input_decorator.dart @@ -2079,7 +2079,6 @@ class _InputDecoratorState extends State with TickerProviderStat if (_hasError) MaterialState.error, }; - InputBorder _getDefaultBorder(ThemeData themeData, InputDecorationTheme defaults) { final InputBorder border = MaterialStateProperty.resolveAs(decoration.border, materialState) ?? const UnderlineInputBorder(); diff --git a/packages/flutter/lib/src/material/menu_anchor.dart b/packages/flutter/lib/src/material/menu_anchor.dart index 4248ae25b0d..b5757619541 100644 --- a/packages/flutter/lib/src/material/menu_anchor.dart +++ b/packages/flutter/lib/src/material/menu_anchor.dart @@ -406,7 +406,7 @@ class _MenuAnchorState extends State { ); } - Widget child = OverlayPortal.targetsRootOverlay( + Widget child = OverlayPortal( controller: _overlayController, overlayChildBuilder: (BuildContext context) { return _Submenu( @@ -1692,6 +1692,7 @@ class SubmenuButton extends StatefulWidget { this.statesController, this.leadingIcon, this.trailingIcon, + this.submenuIcon, required this.menuChildren, required this.child, }); @@ -1756,6 +1757,18 @@ class SubmenuButton extends StatefulWidget { /// An optional icon to display before the [child]. final Widget? leadingIcon; + /// If provided, the widget replaces the default [SubmenuButton] arrow icon. + /// + /// Resolves in the following states: + /// * [WidgetState.disabled]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// + /// If this is null, then the value of [MenuThemeData.submenuIcon] is used. + /// If that is also null, then defaults to a right arrow icon with the size + /// of 24 pixels. + final MaterialStateProperty? submenuIcon; + /// An optional icon to display after the [child]. final Widget? trailingIcon; @@ -1982,6 +1995,17 @@ class _SubmenuButtonState extends State { (Axis.vertical, TextDirection.rtl) => Offset(0, -menuPadding.top), (Axis.vertical, TextDirection.ltr) => Offset(0, -menuPadding.top), }; + final Set states = { + if (!_enabled) MaterialState.disabled, + if (_isHovered) MaterialState.hovered, + if (_buttonFocusNode.hasFocus) MaterialState.focused, + }; + final Widget submenuIcon = widget.submenuIcon?.resolve(states) + ?? MenuTheme.of(context).submenuIcon?.resolve(states) + ?? const Icon( + Icons.arrow_right, // Automatically switches with text direction. + size: _kDefaultSubmenuIconSize, + ); return Actions( actions: actions, @@ -2055,6 +2079,7 @@ class _SubmenuButtonState extends State { trailingIcon: widget.trailingIcon, hasSubmenu: true, showDecoration: (controller._anchor!._parent?._orientation ?? Axis.horizontal) == Axis.vertical, + submenuIcon: submenuIcon, child: child, ), ), @@ -3059,6 +3084,7 @@ class _MenuItemLabel extends StatelessWidget { this.shortcut, this.semanticsLabel, this.overflowAxis = Axis.vertical, + this.submenuIcon, this.child, }); @@ -3089,6 +3115,9 @@ class _MenuItemLabel extends StatelessWidget { /// The direction in which the menu item expands. final Axis overflowAxis; + /// The submenu icon that is displayed when [showDecoration] and [hasSubmenu] are true. + final Widget? submenuIcon; + /// An optional child widget that is displayed in the label. final Widget? child; @@ -3156,10 +3185,7 @@ class _MenuItemLabel extends StatelessWidget { if (showDecoration && hasSubmenu) Padding( padding: EdgeInsetsDirectional.only(start: horizontalPadding), - child: const Icon( - Icons.arrow_right, // Automatically switches with text direction. - size: _kDefaultSubmenuIconSize, - ), + child: submenuIcon, ), ], ); diff --git a/packages/flutter/lib/src/material/menu_theme.dart b/packages/flutter/lib/src/material/menu_theme.dart index be6ee9ad49b..38e62c3642c 100644 --- a/packages/flutter/lib/src/material/menu_theme.dart +++ b/packages/flutter/lib/src/material/menu_theme.dart @@ -8,6 +8,7 @@ library; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; +import 'material_state.dart'; import 'menu_anchor.dart'; import 'menu_style.dart'; import 'theme.dart'; @@ -36,7 +37,10 @@ import 'theme.dart'; @immutable class MenuThemeData with Diagnosticable { /// Creates a const set of properties used to configure [MenuTheme]. - const MenuThemeData({this.style}); + const MenuThemeData({ + this.style, + this.submenuIcon, + }); /// The [MenuStyle] of a [SubmenuButton] menu. /// @@ -44,16 +48,30 @@ class MenuThemeData with Diagnosticable { /// property. final MenuStyle? style; + /// If provided, the widget replaces the default [SubmenuButton] arrow icon. + /// + /// Resolves in the following states: + /// * [WidgetState.disabled]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + final MaterialStateProperty? submenuIcon; + /// Linearly interpolate between two menu button themes. static MenuThemeData? lerp(MenuThemeData? a, MenuThemeData? b, double t) { if (identical(a, b)) { return a; } - return MenuThemeData(style: MenuStyle.lerp(a?.style, b?.style, t)); + return MenuThemeData( + style: MenuStyle.lerp(a?.style, b?.style, t), + submenuIcon: t < 0.5 ? a?.submenuIcon : b?.submenuIcon, + ); } @override - int get hashCode => style.hashCode; + int get hashCode => Object.hash( + style, + submenuIcon, + ); @override bool operator ==(Object other) { @@ -63,13 +81,16 @@ class MenuThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is MenuThemeData && other.style == style; + return other is MenuThemeData + && other.style == style + && other.submenuIcon == submenuIcon; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('style', style, defaultValue: null)); + properties.add(DiagnosticsProperty>('submenuIcon', submenuIcon, defaultValue: null)); } } diff --git a/packages/flutter/lib/src/material/navigation_bar.dart b/packages/flutter/lib/src/material/navigation_bar.dart index 5c1311f1632..678971499ef 100644 --- a/packages/flutter/lib/src/material/navigation_bar.dart +++ b/packages/flutter/lib/src/material/navigation_bar.dart @@ -111,6 +111,7 @@ class NavigationBar extends StatelessWidget { this.height, this.labelBehavior, this.overlayColor, + this.labelTextStyle, this.labelPadding, }) : assert(destinations.length >= 2), assert(0 <= selectedIndex && selectedIndex < destinations.length); @@ -224,6 +225,19 @@ class NavigationBar extends StatelessWidget { /// the [NavigationDestination] is focused, hovered, or pressed. final MaterialStateProperty? overlayColor; + //// The text style of the label. + /// + /// If null, [NavigationBarThemeData.labelTextStyle] is used. If that + /// is also null, the default text style is [TextTheme.labelMedium] with + /// [ColorScheme.onSurface] when the destination is selected, and + /// [ColorScheme.onSurfaceVariant] when the destination is unselected, and + /// [ColorScheme.onSurfaceVariant] with an opacity of 0.38 when the + /// destination is disabled. + /// + /// If [ThemeData.useMaterial3] is false, then the default text style is + /// [TextTheme.labelSmall] with [ColorScheme.onSurface]. + final MaterialStateProperty? labelTextStyle; + /// The padding around the [NavigationDestination.label] widget. /// /// When [labelPadding] is null, [NavigationBarThemeData.labelPadding] @@ -275,6 +289,7 @@ class NavigationBar extends StatelessWidget { indicatorShape: indicatorShape, overlayColor: overlayColor, onTap: _handleTap(i), + labelTextStyle: labelTextStyle, labelPadding: labelPadding, child: destinations[i], ); @@ -426,11 +441,14 @@ class NavigationDestination extends StatelessWidget { ); }, buildLabel: (BuildContext context) { - final TextStyle? effectiveSelectedLabelTextStyle = navigationBarTheme.labelTextStyle?.resolve(selectedState) + final TextStyle? effectiveSelectedLabelTextStyle = info.labelTextStyle?.resolve(selectedState) + ?? navigationBarTheme.labelTextStyle?.resolve(selectedState) ?? defaults.labelTextStyle!.resolve(selectedState); - final TextStyle? effectiveUnselectedLabelTextStyle = navigationBarTheme.labelTextStyle?.resolve(unselectedState) + final TextStyle? effectiveUnselectedLabelTextStyle = info.labelTextStyle?.resolve(unselectedState) + ?? navigationBarTheme.labelTextStyle?.resolve(unselectedState) ?? defaults.labelTextStyle!.resolve(unselectedState); - final TextStyle? effectiveDisabledLabelTextStyle = navigationBarTheme.labelTextStyle?.resolve(disabledState) + final TextStyle? effectiveDisabledLabelTextStyle = info.labelTextStyle?.resolve(disabledState) + ?? navigationBarTheme.labelTextStyle?.resolve(disabledState) ?? defaults.labelTextStyle!.resolve(disabledState); final EdgeInsetsGeometry labelPadding = info.labelPadding ?? navigationBarTheme.labelPadding @@ -604,6 +622,7 @@ class _NavigationDestinationInfo extends InheritedWidget { required this.indicatorShape, required this.overlayColor, required this.onTap, + this.labelTextStyle, this.labelPadding, required super.child, }); @@ -682,6 +701,9 @@ class _NavigationDestinationInfo extends InheritedWidget { /// with [index] passed in. final VoidCallback onTap; + /// The text style of the label. + final MaterialStateProperty? labelTextStyle; + /// The padding around the [label] widget. /// /// Defaults to a padding of 4 pixels on the top. diff --git a/packages/flutter/lib/src/material/navigation_drawer.dart b/packages/flutter/lib/src/material/navigation_drawer.dart index 3cb24aecf07..ae07566010d 100644 --- a/packages/flutter/lib/src/material/navigation_drawer.dart +++ b/packages/flutter/lib/src/material/navigation_drawer.dart @@ -10,6 +10,7 @@ import 'package:flutter/widgets.dart'; import 'color_scheme.dart'; import 'colors.dart'; import 'drawer.dart'; +import 'ink_decoration.dart'; import 'ink_well.dart'; import 'material.dart'; import 'material_localizations.dart'; @@ -196,9 +197,12 @@ class NavigationDrawerDestination extends StatelessWidget { this.enabled = true, }); - /// Sets the color of the destination. + /// The background color of the destination. /// - /// If this is null, then [NavigationDrawerThemeData.backgroundColor]. + /// If this is null, no background is set and [NavigationDrawer.backgroundColor] will be visible. + /// + /// This is the background color of the whole rectangular area behind the drawer destination. + /// To customize only the indicator color consider using [NavigationDrawer.indicatorColor]. final Color? backgroundColor; /// The [Widget] (usually an [Icon]) that's displayed for this @@ -339,9 +343,6 @@ class _NavigationDestinationBuilder extends StatelessWidget { /// Defaults to true. final bool enabled; - /// Sets the color of navigation destination. - /// - /// If this is null, then [NavigationDrawerThemeData.backgroundColor] is used. final Color? backgroundColor; @override @@ -386,9 +387,8 @@ class _NavigationDestinationBuilder extends StatelessWidget { ), ); - final Color? color = backgroundColor ?? navigationDrawerTheme.backgroundColor; - if (color != null) { - return ColoredBox(color: color, child: destination); + if (backgroundColor != null) { + return Ink(color: backgroundColor, child: destination); } return destination; } diff --git a/packages/flutter/lib/src/material/outlined_button.dart b/packages/flutter/lib/src/material/outlined_button.dart index d35af8c528b..5cb79b2d83a 100644 --- a/packages/flutter/lib/src/material/outlined_button.dart +++ b/packages/flutter/lib/src/material/outlined_button.dart @@ -84,7 +84,6 @@ class OutlinedButton extends ButtonStyleButton { super.clipBehavior, super.statesController, required super.child, - super.iconAlignment, }); /// Create a text button from a pair of widgets that serve as the button's @@ -110,7 +109,7 @@ class OutlinedButton extends ButtonStyleButton { MaterialStatesController? statesController, Widget? icon, required Widget label, - IconAlignment iconAlignment = IconAlignment.start, + IconAlignment? iconAlignment, }) { if (icon == null) { return OutlinedButton( @@ -197,6 +196,7 @@ class OutlinedButton extends ButtonStyleButton { Color? surfaceTintColor, Color? iconColor, double? iconSize, + IconAlignment? iconAlignment, Color? disabledIconColor, Color? overlayColor, double? elevation, @@ -243,6 +243,7 @@ class OutlinedButton extends ButtonStyleButton { surfaceTintColor: ButtonStyleButton.allOrNull(surfaceTintColor), iconColor: ButtonStyleButton.defaultColor(iconColor, disabledIconColor), iconSize: ButtonStyleButton.allOrNull(iconSize), + iconAlignment: iconAlignment, elevation: ButtonStyleButton.allOrNull(elevation), padding: ButtonStyleButton.allOrNull(padding), minimumSize: ButtonStyleButton.allOrNull(minimumSize), @@ -427,7 +428,7 @@ class _OutlinedButtonWithIcon extends OutlinedButton { super.statesController, required Widget icon, required Widget label, - super.iconAlignment, + IconAlignment? iconAlignment, }) : super( autofocus: autofocus ?? false, child: _OutlinedButtonWithIconChild( @@ -470,16 +471,21 @@ class _OutlinedButtonWithIconChild extends StatelessWidget { final Widget label; final Widget icon; final ButtonStyle? buttonStyle; - final IconAlignment iconAlignment; + final IconAlignment? iconAlignment; @override Widget build(BuildContext context) { final double defaultFontSize = buttonStyle?.textStyle?.resolve(const {})?.fontSize ?? 14.0; final double scale = clampDouble(MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0, 1.0, 2.0) - 1.0; final double gap = lerpDouble(8, 4, scale)!; + final OutlinedButtonThemeData outlinedButtonTheme = OutlinedButtonTheme.of(context); + final IconAlignment effectiveIconAlignment = iconAlignment + ?? outlinedButtonTheme.style?.iconAlignment + ?? buttonStyle?.iconAlignment + ?? IconAlignment.start; return Row( mainAxisSize: MainAxisSize.min, - children: iconAlignment == IconAlignment.start + children: effectiveIconAlignment == IconAlignment.start ? [icon, SizedBox(width: gap), Flexible(child: label)] : [Flexible(child: label), SizedBox(width: gap), icon], ); diff --git a/packages/flutter/lib/src/material/page.dart b/packages/flutter/lib/src/material/page.dart index 2b87aaa9783..649c388c878 100644 --- a/packages/flutter/lib/src/material/page.dart +++ b/packages/flutter/lib/src/material/page.dart @@ -87,7 +87,40 @@ mixin MaterialRouteTransitionMixin on PageRoute { Widget buildContent(BuildContext context); @override - Duration get transitionDuration => const Duration(milliseconds: 300); + Duration get transitionDuration => _getPageTransitionBuilder(navigator!.context)?.transitionDuration + ?? const Duration(microseconds: 300); + + @override + Duration get reverseTransitionDuration => _getPageTransitionBuilder(navigator!.context)?.reverseTransitionDuration + ?? const Duration(microseconds: 300); + + PageTransitionsBuilder? _getPageTransitionBuilder(BuildContext context) { + final TargetPlatform platform = Theme.of(context).platform; + final PageTransitionsTheme pageTransitionsTheme = Theme.of(context).pageTransitionsTheme; + return pageTransitionsTheme.builders[platform]; + } + + // The transitionDuration is used to create the AnimationController which is only + // built once, so when page transition builder is updated and transitionDuration + // has a new value, the AnimationController cannot be updated automatically. So we + // manually update its duration here. + // TODO(quncCccccc): Clean up this override method when controller can be updated as the transitionDuration is changed. + @override + TickerFuture didPush() { + controller?.duration = transitionDuration; + return super.didPush(); + } + + // The reverseTransitionDuration is used to create the AnimationController + // which is only built once, so when page transition builder is updated and + // reverseTransitionDuration has a new value, the AnimationController cannot + // be updated automatically. So we manually update its reverseDuration here. + // TODO(quncCccccc): Clean up this override method when controller can beupdated as the reverseTransitionDuration is changed. + @override + bool didPop(T? result) { + controller?.reverseDuration = reverseTransitionDuration; + return super.didPop(result); + } @override Color? get barrierColor => null; @@ -124,6 +157,12 @@ mixin MaterialRouteTransitionMixin on PageRoute { ((nextRoute is MaterialRouteTransitionMixin) || nextRouteHasDelegatedTransition); } + @override + bool canTransitionFrom(TransitionRoute previousRoute) { + // Supress previous route from transitioning if this is a fullscreenDialog route. + return previousRoute is PageRoute && !fullscreenDialog; + } + @override Widget buildPage( BuildContext context, diff --git a/packages/flutter/lib/src/material/page_transitions_theme.dart b/packages/flutter/lib/src/material/page_transitions_theme.dart index 940937d9666..c2dc23300a6 100644 --- a/packages/flutter/lib/src/material/page_transitions_theme.dart +++ b/packages/flutter/lib/src/material/page_transitions_theme.dart @@ -534,6 +534,76 @@ class _ZoomExitTransitionState extends State<_ZoomExitTransition> with _ZoomTran } } +// This transition slides a new page in from right to left while fading it in, +// and simultaneously slides the previous page out to the left while fading it out. +// This transition is designed to match the Android U activity transition. +class _FadeForwardsPageTransition extends StatelessWidget { + const _FadeForwardsPageTransition({ + required this.animation, + required this.secondaryAnimation, + this.backgroundColor, + this.child, + }); + + final Animation animation; + + final Animation secondaryAnimation; + + final Color? backgroundColor; + + final Widget? child; + + // The new page slides in from right to left. + static final Animatable _forwardTranslationTween = Tween( + begin: const Offset(0.25, 0.0), + end: Offset.zero, + ).chain(CurveTween(curve: FadeForwardsPageTransitionsBuilder._transitionCurve)); + + // The old page slides back from left to right. + static final Animatable _backwardTranslationTween = Tween( + begin: Offset.zero, + end: const Offset(0.25, 0.0), + ).chain(CurveTween(curve: FadeForwardsPageTransitionsBuilder._transitionCurve)); + + @override + Widget build(BuildContext context) { + return DualTransitionBuilder( + animation: animation, + forwardBuilder: ( + BuildContext context, + Animation animation, + Widget? child + ) { + return FadeTransition( + opacity: FadeForwardsPageTransitionsBuilder._fadeInTransition.animate(animation), + child: SlideTransition( + position: _forwardTranslationTween.animate(animation), + child: child, + ), + ); + }, + reverseBuilder: ( + BuildContext context, + Animation animation, + Widget? child + ) { + return FadeTransition( + opacity: FadeForwardsPageTransitionsBuilder._fadeOutTransition.animate(animation), + child: SlideTransition( + position: _backwardTranslationTween.animate(animation), + child: child, + ), + ); + }, + child: FadeForwardsPageTransitionsBuilder._delegatedTransition( + context, + secondaryAnimation, + backgroundColor, + child, + )); + } +} + /// Used by [PageTransitionsTheme] to define a [MaterialPageRoute] page /// transition animation. /// @@ -551,16 +621,28 @@ class _ZoomExitTransitionState extends State<_ZoomExitTransition> with _ZoomTran /// that's similar to the one provided in Android Q. /// * [CupertinoPageTransitionsBuilder], which defines a horizontal page /// transition that matches native iOS page transitions. +/// * [FadeForwardsPageTransitionsBuilder], which defines a page transition +/// that's similar to the one provided by Android U. abstract class PageTransitionsBuilder { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. const PageTransitionsBuilder(); - /// Provideds a secondary transition to the previous route. + /// Provides a secondary transition to the previous route. /// /// {@macro flutter.widgets.delegatedTransition} DelegatedTransitionBuilder? get delegatedTransition => null; + /// {@macro flutter.widgets.TransitionRoute.transitionDuration} + /// + /// Defaults to 300 milliseconds. + Duration get transitionDuration => const Duration(milliseconds: 300); + + /// {@macro flutter.widgets.TransitionRoute.reverseTransitionDuration} + /// + /// Defaults to 300 milliseconds. + Duration get reverseTransitionDuration => transitionDuration; + /// Wraps the child with one or more transition widgets which define how [route] /// arrives on and leaves the screen. /// @@ -625,6 +707,8 @@ class FadeUpwardsPageTransitionsBuilder extends PageTransitionsBuilder { /// transition that matches native iOS page transitions. /// * [PredictiveBackPageTransitionsBuilder], which defines a page /// transition that allows peeking behind the current route on Android. +/// * [FadeForwardsPageTransitionsBuilder], which defines a page transition +/// that's similar to the one provided by Android U. class OpenUpwardsPageTransitionsBuilder extends PageTransitionsBuilder { /// Constructs a page transition animation that matches the transition used on /// Android P. @@ -646,6 +730,143 @@ class OpenUpwardsPageTransitionsBuilder extends PageTransitionsBuilder { } } +/// Used by [PageTransitionsTheme] to define a horizontal [MaterialPageRoute] page +/// transition animation that looks like the default page transition +/// used on Android U. +/// +/// {@tool dartpad} +/// This example shows the default page transition on Android. +/// +/// ** See code in examples/api/lib/material/page_transitions_theme/page_transitions_theme.3.dart ** +/// {@end-tool} +/// +/// See also: +/// +/// * [FadeUpwardsPageTransitionsBuilder], which defines a page transition +/// that's similar to the one provided by Android O. +/// * [OpenUpwardsPageTransitionsBuilder], which defines a page transition +/// that's similar to the one provided by Andoird P. +/// * [ZoomPageTransitionsBuilder], which defines the default page transition +/// that's similar to the one provided in Android Q. +/// * [CupertinoPageTransitionsBuilder], which defines a horizontal page +/// transition that matches native iOS page transitions. +/// * [PredictiveBackPageTransitionsBuilder], which defines a page +/// transition that allows peeking behind the current route on Android. +/// * [FadeForwardsPageTransitionsBuilder], which defines a page transition +/// that's similar to the one provided by Android U. +class FadeForwardsPageTransitionsBuilder extends PageTransitionsBuilder { + /// Constructs a page transition animation that matches the transition used on + /// Android U. + const FadeForwardsPageTransitionsBuilder({ + this.backgroundColor, + }); + + /// The background color during transition between two routes. + /// + /// When a new page fades in and the old page fades out, this background color + /// helps avoid a black background between two page. + /// + /// Defaults to [ColorScheme.surface] + final Color? backgroundColor; + + @override + Duration get transitionDuration => const Duration(milliseconds: 800); + + @override + DelegatedTransitionBuilder? get delegatedTransition => (BuildContext context, Animation animation, Animation secondaryAnimation, bool allowSnapshotting, Widget? child) + => _delegatedTransition(context, animation, backgroundColor, child); + + // Used by all of the sliding transition animations. + static const Curve _transitionCurve = Curves.easeInOutCubicEmphasized; + + // The previous page slides from right to left as the current page appears. + static final Animatable _secondaryBackwardTranslationTween = Tween( + begin: Offset.zero, + end: const Offset(-0.25, 0.0), + ).chain(CurveTween(curve: _transitionCurve)); + + // The previous page slides from left to right as the current page disappears. + static final Animatable _secondaryForwardTranslationTween = Tween( + begin: const Offset(-0.25, 0.0), + end: Offset.zero, + ).chain(CurveTween(curve: _transitionCurve)); + + // The fade in transition when the new page appears. + static final Animatable _fadeInTransition = Tween( + begin: 0.0, + end: 1.0, + ).chain(CurveTween(curve: const Interval(0.0, 0.75))); + + // The fade out transition of the old page when the new page appears. + static final Animatable _fadeOutTransition = Tween( + begin: 1.0, + end: 0.0, + ).chain(CurveTween(curve: const Interval(0.0, 0.25))); + + static Widget _delegatedTransition( + BuildContext context, + Animation secondaryAnimation, + Color? backgroundColor, + Widget? child, + ) => DualTransitionBuilder( + animation: ReverseAnimation(secondaryAnimation), + forwardBuilder: ( + BuildContext context, + Animation animation, + Widget? child + ) { + return ColoredBox( + color: animation.isAnimating + ? backgroundColor ?? Theme.of(context).colorScheme.surface + : Colors.transparent, + child: FadeTransition( + opacity: _fadeInTransition.animate(animation), + child: SlideTransition( + position: _secondaryForwardTranslationTween.animate(animation), + child: child, + ), + ), + ); + }, + reverseBuilder: ( + BuildContext context, + Animation animation, + Widget? child + ) { + return ColoredBox( + color: animation.isAnimating + ? backgroundColor ?? Theme.of(context).colorScheme.surface + : Colors.transparent, + child: FadeTransition( + opacity: _fadeOutTransition.animate(animation), + child: SlideTransition( + position: _secondaryBackwardTranslationTween.animate(animation), + child: child, + ), + ), + ); + }, + child: child, + ); + + + @override + Widget buildTransitions( + PageRoute? route, + BuildContext? context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) { + return _FadeForwardsPageTransition( + animation: animation, + secondaryAnimation: secondaryAnimation, + backgroundColor: backgroundColor, + child: child, + ); + } +} + /// Used by [PageTransitionsTheme] to define a zooming [MaterialPageRoute] page /// transition animation that looks like the default page transition used on /// Android Q. @@ -660,6 +881,8 @@ class OpenUpwardsPageTransitionsBuilder extends PageTransitionsBuilder { /// transition that matches native iOS page transitions. /// * [PredictiveBackPageTransitionsBuilder], which defines a page /// transition that allows peeking behind the current route on Android. +/// * [FadeForwardsPageTransitionsBuilder], which defines a page transition +/// that's similar to the one provided by Android U. class ZoomPageTransitionsBuilder extends PageTransitionsBuilder { /// Constructs a page transition animation that matches the transition used on /// Android Q. @@ -836,6 +1059,8 @@ class CupertinoPageTransitionsBuilder extends PageTransitionsBuilder { /// that's similar to the one provided by Android P. /// * [ZoomPageTransitionsBuilder], which defines the default page transition /// that's similar to the one provided by Android Q. +/// * [FadeForwardsPageTransitionsBuilder], which defines the default page transition +/// that's similar to the one provided by Android U. /// * [CupertinoPageTransitionsBuilder], which defines a horizontal page /// transition that matches native iOS page transitions. @immutable diff --git a/packages/flutter/lib/src/material/paginated_data_table.dart b/packages/flutter/lib/src/material/paginated_data_table.dart index 06523ca034c..96c6342d72b 100644 --- a/packages/flutter/lib/src/material/paginated_data_table.dart +++ b/packages/flutter/lib/src/material/paginated_data_table.dart @@ -331,6 +331,7 @@ class PaginatedDataTableState extends State { int _selectedRowCount = 0; final Map _rows = {}; + @protected @override void initState() { super.initState(); @@ -339,6 +340,7 @@ class PaginatedDataTableState extends State { _handleDataSourceChanged(); } + @protected @override void didUpdateWidget(PaginatedDataTable oldWidget) { super.didUpdateWidget(oldWidget); @@ -349,6 +351,7 @@ class PaginatedDataTableState extends State { } } + @protected @override void reassemble() { super.reassemble(); @@ -366,6 +369,7 @@ class PaginatedDataTableState extends State { _updateCaches(); } + @protected @override void dispose() { widget.source.removeListener(_handleDataSourceChanged); @@ -468,6 +472,7 @@ class PaginatedDataTableState extends State { final GlobalKey _tableKey = GlobalKey(); + @protected @override Widget build(BuildContext context) { // TODO(ianh): This whole build function doesn't handle RTL yet. diff --git a/packages/flutter/lib/src/material/popup_menu.dart b/packages/flutter/lib/src/material/popup_menu.dart index ebbe302d716..0a8b65612d8 100644 --- a/packages/flutter/lib/src/material/popup_menu.dart +++ b/packages/flutter/lib/src/material/popup_menu.dart @@ -28,6 +28,7 @@ import 'material_state.dart'; import 'popup_menu_theme.dart'; import 'text_theme.dart'; import 'theme.dart'; +import 'theme_data.dart'; import 'tooltip.dart'; // Examples can assume: @@ -355,6 +356,7 @@ class PopupMenuItemState> extends State { widget.onTap?.call(); } + @protected @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); @@ -850,7 +852,8 @@ class _PopupMenuRouteLayout extends SingleChildLayoutDelegate { class _PopupMenuRoute extends PopupRoute { _PopupMenuRoute({ - required this.position, + this.position, + this.positionBuilder, required this.items, required this.itemKeys, this.initialValue, @@ -868,12 +871,15 @@ class _PopupMenuRoute extends PopupRoute { super.settings, super.requestFocus, this.popUpAnimationStyle, - }) : itemSizes = List.filled(items.length, null), + }) : assert((position != null) != (positionBuilder != null), + 'Either position or positionBuilder must be provided.'), + itemSizes = List.filled(items.length, null), // Menus always cycle focus through their items irrespective of the // focus traversal edge behavior set in the Navigator. super(traversalEdgeBehavior: TraversalEdgeBehavior.closedLoop); - final RelativeRect position; + final RelativeRect? position; + final PopupMenuPositionBuilder? positionBuilder; final List> items; final List itemKeys; final List itemSizes; @@ -953,11 +959,11 @@ class _PopupMenuRoute extends PopupRoute { removeBottom: true, removeLeft: true, removeRight: true, - child: Builder( - builder: (BuildContext context) { + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { return CustomSingleChildLayout( delegate: _PopupMenuRouteLayout( - position, + positionBuilder?.call(context, constraints) ?? position!, itemSizes, selectedItemIndex, Directionality.of(context), @@ -982,10 +988,39 @@ class _PopupMenuRoute extends PopupRoute { } } -/// Show a popup menu that contains the `items` at `position`. +/// A builder that creates a [RelativeRect] to position a popup menu. +/// Both [BuildContext] and [BoxConstraints] are from the [PopupRoute] that +/// displays this menu. +/// +/// The returned [RelativeRect] determines the position of the popup menu relative +/// to the bounds of the [Navigator]'s overlay. The menu dimensions are not yet +/// known when this callback is invoked, as they depend on the items and other +/// properties of the menu. +/// +/// The coordinate system used by the [RelativeRect] has its origin at the top +/// left of the [Navigator]'s overlay. Positive y coordinates are down (below the +/// origin), and positive x coordinates are to the right of the origin. +/// +/// See also: +/// +/// * [RelativeRect.fromLTRB], which creates a [RelativeRect] from left, top, +/// right, and bottom coordinates. +/// * [RelativeRect.fromRect], which creates a [RelativeRect] from two [Rect]s, +/// one representing the size of the popup menu and one representing the size +/// of the overlay. +typedef PopupMenuPositionBuilder = RelativeRect Function( + BuildContext context, BoxConstraints constraints); + +/// Shows a popup menu that contains the `items` at `position`. /// /// The `items` parameter must not be empty. /// +/// Only one of [position] or [positionBuilder] should be provided. Providing both +/// throws an assertion error. The [positionBuilder] is called at the time the +/// menu is shown to compute its position and every time the layout is updated, +/// which is useful when the position needs +/// to be determined at runtime based on the current layout. +/// /// If `initialValue` is specified then the first item with a matching value /// will be highlighted and the value of `position` gives the rectangle whose /// vertical center will be aligned with the vertical center of the highlighted @@ -1045,7 +1080,8 @@ class _PopupMenuRoute extends PopupRoute { /// semantics. Future showMenu({ required BuildContext context, - required RelativeRect position, + RelativeRect? position, + PopupMenuPositionBuilder? positionBuilder, required List> items, T? initialValue, double? elevation, @@ -1064,6 +1100,8 @@ Future showMenu({ }) { assert(items.isNotEmpty); assert(debugCheckHasMaterialLocalizations(context)); + assert((position != null) != (positionBuilder != null), + 'Either position or positionBuilder must be provided.'); switch (Theme.of(context).platform) { case TargetPlatform.iOS: @@ -1080,6 +1118,7 @@ Future showMenu({ final NavigatorState navigator = Navigator.of(context, rootNavigator: useRootNavigator); return navigator.push(_PopupMenuRoute( position: position, + positionBuilder: positionBuilder, items: items, itemKeys: menuItemKeys, initialValue: initialValue, @@ -1466,15 +1505,8 @@ class PopupMenuButton extends StatefulWidget { /// See [showButtonMenu] for a way to programmatically open the popup menu /// of your button state. class PopupMenuButtonState extends State> { - /// A method to show a popup menu with the items supplied to - /// [PopupMenuButton.itemBuilder] at the position of your [PopupMenuButton]. - /// - /// By default, it is called when the user taps the button and [PopupMenuButton.enabled] - /// is set to `true`. Moreover, you can open the button by calling the method manually. - /// - /// You would access your [PopupMenuButtonState] using a [GlobalKey] and - /// show the menu of the button with `globalKey.currentState.showButtonMenu`. - void showButtonMenu() { + + RelativeRect _positionBuilder(BuildContext _, BoxConstraints constraints) { final PopupMenuThemeData popupMenuTheme = PopupMenuTheme.of(context); final RenderBox button = context.findRenderObject()! as RenderBox; final RenderBox overlay = Navigator.of( @@ -1500,6 +1532,20 @@ class PopupMenuButtonState extends State> { ), Offset.zero & overlay.size, ); + + return position; + } + + /// A method to show a popup menu with the items supplied to + /// [PopupMenuButton.itemBuilder] at the position of your [PopupMenuButton]. + /// + /// By default, it is called when the user taps the button and [PopupMenuButton.enabled] + /// is set to `true`. Moreover, you can open the button by calling the method manually. + /// + /// You would access your [PopupMenuButtonState] using a [GlobalKey] and + /// show the menu of the button with `globalKey.currentState.showButtonMenu`. + void showButtonMenu() { + final PopupMenuThemeData popupMenuTheme = PopupMenuTheme.of(context); final List> items = widget.itemBuilder(context); // Only show the menu if there is something to show if (items.isNotEmpty) { @@ -1511,7 +1557,7 @@ class PopupMenuButtonState extends State> { surfaceTintColor: widget.surfaceTintColor ?? popupMenuTheme.surfaceTintColor, items: items, initialValue: widget.initialValue, - position: position, + positionBuilder: _positionBuilder, shape: widget.shape ?? popupMenuTheme.shape, menuPadding: widget.menuPadding ?? popupMenuTheme.menuPadding, color: widget.color ?? popupMenuTheme.color, @@ -1543,6 +1589,7 @@ class PopupMenuButtonState extends State> { }; } + @protected @override Widget build(BuildContext context) { final IconThemeData iconTheme = IconTheme.of(context); @@ -1554,7 +1601,7 @@ class PopupMenuButtonState extends State> { assert(debugCheckHasMaterialLocalizations(context)); if (widget.child != null) { - return Tooltip( + final Widget child = Tooltip( message: widget.tooltip ?? MaterialLocalizations.of(context).showMenuTooltip, child: InkWell( borderRadius: widget.borderRadius, @@ -1565,6 +1612,17 @@ class PopupMenuButtonState extends State> { child: widget.child, ), ); + final MaterialTapTargetSize tapTargetSize = widget.style?.tapTargetSize ?? MaterialTapTargetSize.shrinkWrap; + if (tapTargetSize == MaterialTapTargetSize.padded) { + return ConstrainedBox( + constraints: const BoxConstraints( + minWidth: kMinInteractiveDimension, + minHeight: kMinInteractiveDimension, + ), + child: child, + ); + } + return child; } return IconButton( diff --git a/packages/flutter/lib/src/material/progress_indicator.dart b/packages/flutter/lib/src/material/progress_indicator.dart index 0b454bda51d..a1b4085ebab 100644 --- a/packages/flutter/lib/src/material/progress_indicator.dart +++ b/packages/flutter/lib/src/material/progress_indicator.dart @@ -17,7 +17,6 @@ import 'material.dart'; import 'progress_indicator_theme.dart'; import 'theme.dart'; -const double _kMinCircularProgressIndicatorSize = 36.0; const int _kIndeterminateLinearDuration = 1800; const int _kIndeterminateCircularDuration = 1333 * 2222; @@ -313,6 +312,8 @@ class _LinearProgressIndicatorPainter extends CustomPainter { /// /// {@tool dartpad} /// This example showcases determinate and indeterminate [LinearProgressIndicator]s. +/// The [LinearProgressIndicator]s will use the ![updated Material 3 Design appearance](https://m3.material.io/components/progress-indicators/overview) +/// when setting the [LinearProgressIndicator.year2023] flag to false. /// /// ** See code in examples/api/lib/material/progress_indicator/linear_progress_indicator.0.dart ** /// {@end-tool} @@ -352,7 +353,7 @@ class LinearProgressIndicator extends ProgressIndicator { 'Use ProgressIndicatorTheme to customize the ProgressIndicator appearance. ' 'This feature was deprecated after v3.26.0-0.1.pre.' ) - this.year2023 = true, + this.year2023, }) : assert(minHeight == null || minHeight > 0); /// {@template flutter.material.LinearProgressIndicator.trackColor} @@ -415,18 +416,21 @@ class LinearProgressIndicator extends ProgressIndicator { /// If that is null, then defaults to 4. final double? trackGap; - /// When true, the [LinearProgressIndicator] will use the 2023 Material 3 - /// Design appearance. + /// When true, the [LinearProgressIndicator] will use the 2023 Material Design 3 + /// appearance. /// - /// Defaults to true. If false, the [LinearProgressIndicator] will use the - /// latest Material 3 Design appearance, which was introduced in December 2023. + /// If null, then the [ProgressIndicatorThemeData.year2023] will be used. + /// If that is null, then defaults to true. + /// + /// If this is set to false, the [LinearProgressIndicator] will use the + /// latest Material Design 3 appearance, which was introduced in December 2023. /// /// If [ThemeData.useMaterial3] is false, then this property is ignored. @Deprecated( 'Use ProgressIndicatorTheme to customize the ProgressIndicator appearance. ' 'This feature was deprecated after v3.27.0-0.1.pre.' ) - final bool year2023; + final bool? year2023; @override State createState() => _LinearProgressIndicatorState(); @@ -464,14 +468,14 @@ class _LinearProgressIndicatorState extends State with } Widget _buildIndicator(BuildContext context, double animationValue, TextDirection textDirection) { + final ProgressIndicatorThemeData indicatorTheme = ProgressIndicatorTheme.of(context); + final bool year2023 = widget.year2023 ?? indicatorTheme.year2023 ?? true; final ProgressIndicatorThemeData defaults = switch (Theme.of(context).useMaterial3) { - true => widget.year2023 + true => year2023 ? _LinearProgressIndicatorDefaultsM3Year2023(context) : _LinearProgressIndicatorDefaultsM3(context), false => _LinearProgressIndicatorDefaultsM2(context), }; - - final ProgressIndicatorThemeData indicatorTheme = ProgressIndicatorTheme.of(context); final Color trackColor = widget.backgroundColor ?? indicatorTheme.linearTrackColor ?? defaults.linearTrackColor!; @@ -481,17 +485,17 @@ class _LinearProgressIndicatorState extends State with final BorderRadiusGeometry? borderRadius = widget.borderRadius ?? indicatorTheme.borderRadius ?? defaults.borderRadius; - final Color? stopIndicatorColor = !widget.year2023 + final Color? stopIndicatorColor = !year2023 ? widget.stopIndicatorColor ?? indicatorTheme.stopIndicatorColor ?? defaults.stopIndicatorColor : null; - final double? stopIndicatorRadius = !widget.year2023 + final double? stopIndicatorRadius = !year2023 ? widget.stopIndicatorRadius ?? indicatorTheme.stopIndicatorRadius ?? defaults.stopIndicatorRadius : null; - final double? trackGap = !widget.year2023 + final double? trackGap = !year2023 ? widget.trackGap ?? indicatorTheme.trackGap ?? defaults.trackGap @@ -550,7 +554,7 @@ class _LinearProgressIndicatorState extends State with class _CircularProgressIndicatorPainter extends CustomPainter { _CircularProgressIndicatorPainter({ - this.backgroundColor, + this.trackColor, required this.valueColor, required this.value, required this.headValue, @@ -560,6 +564,8 @@ class _CircularProgressIndicatorPainter extends CustomPainter { required this.strokeWidth, required this.strokeAlign, this.strokeCap, + this.trackGap, + this.year2023 = true, }) : arcStart = value != null ? _startAngle : _startAngle + tailValue * 3 / 2 * math.pi + rotationValue * math.pi * 2.0 + offsetValue * 0.5 * math.pi, @@ -567,7 +573,7 @@ class _CircularProgressIndicatorPainter extends CustomPainter { ? clampDouble(value, 0.0, 1.0) * _sweep : math.max(headValue * 3 / 2 * math.pi - tailValue * 3 / 2 * math.pi, _epsilon); - final Color? backgroundColor; + final Color? trackColor; final Color valueColor; final double? value; final double headValue; @@ -579,6 +585,8 @@ class _CircularProgressIndicatorPainter extends CustomPainter { final double arcStart; final double arcSweep; final StrokeCap? strokeCap; + final double? trackGap; + final bool year2023; static const double _twoPi = math.pi * 2.0; static const double _epsilon = .001; @@ -601,27 +609,57 @@ class _CircularProgressIndicatorPainter extends CustomPainter { size.width - strokeOffset * 2, size.height - strokeOffset * 2, ); + final bool hasGap = trackGap != null && trackGap! > 0; - if (backgroundColor != null) { + if (trackColor != null) { final Paint backgroundPaint = Paint() - ..color = backgroundColor! + ..color = trackColor! ..strokeWidth = strokeWidth + ..strokeCap = strokeCap ?? StrokeCap.round ..style = PaintingStyle.stroke; - canvas.drawArc( - arcBaseOffset & arcActualSize, - 0, - _sweep, - false, - backgroundPaint, - ); + // If hasGap is true, draw the background arc with a gap. + if (hasGap && value! > _epsilon) { + final double arcRadius = arcActualSize.shortestSide / 2; + final double strokeRadius = strokeWidth / arcRadius; + final double gapRadius = trackGap! / arcRadius; + final double startGap = strokeRadius + gapRadius; + final double endGap = value! < _epsilon ? startGap : startGap * 2; + final double startSweep = (-math.pi / 2.0) + startGap; + final double endSweep = math.max(0.0, _twoPi - clampDouble(value!, 0.0, 1.0) * _twoPi - endGap); + // Flip the canvas for the background arc. + canvas.save(); + canvas.scale(-1, 1); + canvas.translate(-size.width, 0); + canvas.drawArc( + arcBaseOffset & arcActualSize, + startSweep, + endSweep, + false, + backgroundPaint, + ); + // Restore the canvas to draw the foreground arc. + canvas.restore(); + } else { + canvas.drawArc( + arcBaseOffset & arcActualSize, + 0, + _sweep, + false, + backgroundPaint, + ); + } } - if (value == null && strokeCap == null) { - // Indeterminate - paint.strokeCap = StrokeCap.square; + if (year2023) { + if (value == null && strokeCap == null) { + // Indeterminate + paint.strokeCap = StrokeCap.square; + } else { + // Butt when determinate (value != null) && strokeCap == null; + paint.strokeCap = strokeCap ?? StrokeCap.butt; + } } else { - // Butt when determinate (value != null) && strokeCap == null; - paint.strokeCap = strokeCap ?? StrokeCap.butt; + paint.strokeCap = strokeCap ?? StrokeCap.round; } canvas.drawArc( @@ -635,7 +673,7 @@ class _CircularProgressIndicatorPainter extends CustomPainter { @override bool shouldRepaint(_CircularProgressIndicatorPainter oldPainter) { - return oldPainter.backgroundColor != backgroundColor + return oldPainter.trackColor != trackColor || oldPainter.valueColor != valueColor || oldPainter.value != value || oldPainter.headValue != headValue @@ -644,7 +682,9 @@ class _CircularProgressIndicatorPainter extends CustomPainter { || oldPainter.rotationValue != rotationValue || oldPainter.strokeWidth != strokeWidth || oldPainter.strokeAlign != strokeAlign - || oldPainter.strokeCap != strokeCap; + || oldPainter.strokeCap != strokeCap + || oldPainter.trackGap != trackGap + || oldPainter.year2023 != year2023; } } @@ -669,7 +709,9 @@ class _CircularProgressIndicatorPainter extends CustomPainter { /// specify a constant color use: `AlwaysStoppedAnimation(color)`. /// /// {@tool dartpad} -/// This example shows a [CircularProgressIndicator] with a changing value. +/// This example showcases determinate and indeterminate [CircularProgressIndicator]s. +/// The [CircularProgressIndicator]s will use the ![updated Material 3 Design appearance](https://m3.material.io/components/progress-indicators/overview) +/// when setting the [CircularProgressIndicator.year2023] flag to false. /// /// ** See code in examples/api/lib/material/progress_indicator/circular_progress_indicator.0.dart ** /// {@end-tool} @@ -698,19 +740,29 @@ class CircularProgressIndicator extends ProgressIndicator { super.backgroundColor, super.color, super.valueColor, - this.strokeWidth = 4.0, - this.strokeAlign = strokeAlignCenter, + this.strokeWidth, + this.strokeAlign, super.semanticsLabel, super.semanticsValue, this.strokeCap, + this.constraints, + this.trackGap, + @Deprecated( + 'Use ProgressIndicatorTheme to customize the ProgressIndicator appearance. ' + 'This feature was deprecated after v3.27.0-0.1.pre.' + ) + this.year2023, + this.padding, }) : _indicatorType = _ActivityIndicatorType.material; /// Creates an adaptive progress indicator that is a - /// [CupertinoActivityIndicator] in [TargetPlatform.iOS] & [TargetPlatform.macOS] and [CircularProgressIndicator] in - /// material theme/non-Apple platforms. + /// [CupertinoActivityIndicator] on [TargetPlatform.iOS] & + /// [TargetPlatform.macOS] and a [CircularProgressIndicator] in material + /// theme/non-Apple platforms. /// - /// The [value], [valueColor], [strokeWidth], [semanticsLabel], and - /// [semanticsValue] will be ignored in iOS & macOS. + /// The [valueColor], [strokeWidth], [strokeAlign], [strokeCap], + /// [semanticsLabel], [semanticsValue], [trackGap], [year2023] will be + /// ignored on iOS & macOS. /// /// {@macro flutter.material.ProgressIndicator.ProgressIndicator} const CircularProgressIndicator.adaptive({ @@ -722,7 +774,15 @@ class CircularProgressIndicator extends ProgressIndicator { super.semanticsLabel, super.semanticsValue, this.strokeCap, - this.strokeAlign = strokeAlignCenter, + this.strokeAlign, + this.constraints, + this.trackGap, + @Deprecated( + 'Use ProgressIndicatorTheme to customize the ProgressIndicator appearance. ' + 'This feature was deprecated after v3.27.0-0.2.pre.' + ) + this.year2023, + this.padding, }) : _indicatorType = _ActivityIndicatorType.adaptive; final _ActivityIndicatorType _indicatorType; @@ -738,16 +798,19 @@ class CircularProgressIndicator extends ProgressIndicator { Color? get backgroundColor => super.backgroundColor; /// The width of the line used to draw the circle. - final double strokeWidth; + final double? strokeWidth; /// The relative position of the stroke on a [CircularProgressIndicator]. /// /// Values typically range from -1.0 ([strokeAlignInside], inside stroke) /// to 1.0 ([strokeAlignOutside], outside stroke), /// without any bound constraints (e.g., a value of -2.0 is not typical, but allowed). - /// A value of 0 ([strokeAlignCenter], default) will center the border + /// A value of 0 ([strokeAlignCenter]) will center the border /// on the edge of the widget. - final double strokeAlign; + /// + /// If [year2023] is true, then the default value is [strokeAlignCenter]. + /// Otherwise, the default value is [strokeAlignInside]. + final double? strokeAlign; /// The progress indicator's line ending. /// @@ -770,6 +833,46 @@ class CircularProgressIndicator extends ProgressIndicator { /// degrees and end at 275 degrees. final StrokeCap? strokeCap; + /// Defines minimum and maximum sizes for a [CircularProgressIndicator]. + /// + /// If null, then the [ProgressIndicatorThemeData.constraints] will be used. + /// Otherwise, defaults to a minimum width and height of 36 pixels. + final BoxConstraints? constraints; + + /// The gap between the active indicator and the background track. + /// + /// If [year2023] is false or [ThemeData.useMaterial3] is false, then no track + /// gap will be drawn. + /// + /// Set [trackGap] to 0 to hide the track gap. + /// + /// If null, then the [ProgressIndicatorThemeData.trackGap] will be used. + /// If that is null, then defaults to 4. + final double? trackGap; + + /// When true, the [CircularProgressIndicator] will use the 2023 Material Design 3 + /// appearance. + /// + /// If null, then the [ProgressIndicatorThemeData.year2023] will be used. + /// If that is null, then defaults to true. + /// + /// If this is set to false, the [CircularProgressIndicator] will use the + /// latest Material Design 3 appearance, which was introduced in December 2023. + /// + /// If [ThemeData.useMaterial3] is false, then this property is ignored. + @Deprecated( + 'Use ProgressIndicatorTheme to customize the ProgressIndicator appearance. ' + 'This feature was deprecated after v3.27.0-0.2.pre.' + ) + final bool? year2023; + + /// The padding around the indicator track. + /// + /// If null, then the [ProgressIndicatorThemeData.circularTrackPadding] will be + /// used. If that is null and [year2023] is false, then defaults to `EdgeInsets.all(4.0)` + /// padding. Otherwise, defaults to zero padding. + final EdgeInsetsGeometry? padding; + /// The indicator stroke is drawn fully inside of the indicator path. /// /// This is a constant for use with [strokeAlign]. @@ -857,33 +960,67 @@ class _CircularProgressIndicatorState extends State w } Widget _buildMaterialIndicator(BuildContext context, double headValue, double tailValue, double offsetValue, double rotationValue) { - final ProgressIndicatorThemeData defaults = Theme.of(context).useMaterial3 - ? _CircularProgressIndicatorDefaultsM3(context) - : _CircularProgressIndicatorDefaultsM2(context); - final Color? trackColor = widget.backgroundColor ?? ProgressIndicatorTheme.of(context).circularTrackColor; + final ProgressIndicatorThemeData indicatorTheme = ProgressIndicatorTheme.of(context); + final bool year2023 = widget.year2023 ?? indicatorTheme.year2023 ?? true; + final ProgressIndicatorThemeData defaults = switch (Theme.of(context).useMaterial3) { + true => year2023 + ? _CircularProgressIndicatorDefaultsM3Year2023(context, indeterminate: widget.value == null) + : _CircularProgressIndicatorDefaultsM3(context, indeterminate: widget.value == null), + false => _CircularProgressIndicatorDefaultsM2(context, indeterminate: widget.value == null), + }; + final Color? trackColor = widget.backgroundColor + ?? indicatorTheme.circularTrackColor + ?? defaults.circularTrackColor; + final double strokeWidth = widget.strokeWidth + ?? indicatorTheme.strokeWidth + ?? defaults.strokeWidth!; + final double strokeAlign = widget.strokeAlign + ?? indicatorTheme.strokeAlign + ?? defaults.strokeAlign!; + final StrokeCap? strokeCap = widget.strokeCap + ?? indicatorTheme.strokeCap; + final BoxConstraints constraints = widget.constraints + ?? indicatorTheme.constraints + ?? defaults.constraints!; + final double? trackGap = year2023 + ? null + : widget.trackGap ?? + indicatorTheme.trackGap ?? + defaults.trackGap; + final EdgeInsetsGeometry? effectivePadding = widget.padding + ?? indicatorTheme.circularTrackPadding + ?? defaults.circularTrackPadding; + + Widget result = ConstrainedBox( + constraints: constraints, + child: CustomPaint( + painter: _CircularProgressIndicatorPainter( + trackColor: trackColor, + valueColor: widget._getValueColor(context, defaultColor: defaults.color), + value: widget.value, // may be null + headValue: headValue, // remaining arguments are ignored if widget.value is not null + tailValue: tailValue, + offsetValue: offsetValue, + rotationValue: rotationValue, + strokeWidth: strokeWidth, + strokeAlign: strokeAlign, + strokeCap: strokeCap, + trackGap: trackGap, + year2023: year2023, + ), + ), + ); + + if (effectivePadding != null) { + result = Padding( + padding: effectivePadding, + child: result, + ); + } return widget._buildSemanticsWrapper( context: context, - child: ConstrainedBox( - constraints: const BoxConstraints( - minWidth: _kMinCircularProgressIndicatorSize, - minHeight: _kMinCircularProgressIndicatorSize, - ), - child: CustomPaint( - painter: _CircularProgressIndicatorPainter( - backgroundColor: trackColor, - valueColor: widget._getValueColor(context, defaultColor: defaults.color), - value: widget.value, // may be null - headValue: headValue, // remaining arguments are ignored if widget.value is not null - tailValue: tailValue, - offsetValue: offsetValue, - rotationValue: rotationValue, - strokeWidth: widget.strokeWidth, - strokeAlign: widget.strokeAlign, - strokeCap: widget.strokeCap, - ), - ), - ), + child: result, ); } @@ -1128,10 +1265,22 @@ class _RefreshProgressIndicatorState extends _CircularProgressIndicatorState { final double opacity = valueColor.opacity; valueColor = valueColor.withOpacity(1.0); - final Color backgroundColor = - widget.backgroundColor ?? - ProgressIndicatorTheme.of(context).refreshBackgroundColor ?? - Theme.of(context).canvasColor; + final ProgressIndicatorThemeData defaults = switch (Theme.of(context).useMaterial3) { + true => _CircularProgressIndicatorDefaultsM3Year2023(context, indeterminate: value == null), + false => _CircularProgressIndicatorDefaultsM2(context, indeterminate: value == null), + }; + final ProgressIndicatorThemeData indicatorTheme = ProgressIndicatorTheme.of(context); + final Color backgroundColor = widget.backgroundColor + ?? indicatorTheme.refreshBackgroundColor + ?? Theme.of(context).canvasColor; + final double strokeWidth = widget.strokeWidth + ?? indicatorTheme.strokeWidth + ?? defaults.strokeWidth!; + final double strokeAlign = widget.strokeAlign + ?? indicatorTheme.strokeAlign + ?? defaults.strokeAlign!; + final StrokeCap? strokeCap = widget.strokeCap + ?? indicatorTheme.strokeCap; return widget._buildSemanticsWrapper( context: context, @@ -1157,10 +1306,10 @@ class _RefreshProgressIndicatorState extends _CircularProgressIndicatorState { tailValue: tailValue, offsetValue: offsetValue, rotationValue: rotationValue, - strokeWidth: widget.strokeWidth, - strokeAlign: widget.strokeAlign, + strokeWidth: strokeWidth, + strokeAlign: strokeAlign, arrowheadScale: arrowheadScale, - strokeCap: widget.strokeCap, + strokeCap: strokeCap, ), ), ), @@ -1175,13 +1324,26 @@ class _RefreshProgressIndicatorState extends _CircularProgressIndicatorState { // Hand coded defaults based on Material Design 2. class _CircularProgressIndicatorDefaultsM2 extends ProgressIndicatorThemeData { - _CircularProgressIndicatorDefaultsM2(this.context); + _CircularProgressIndicatorDefaultsM2(this.context, { required this.indeterminate }); final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; + final bool indeterminate; @override Color get color => _colors.primary; + + @override + double? get strokeWidth => 4.0; + + @override + double? get strokeAlign => CircularProgressIndicator.strokeAlignCenter; + + @override + BoxConstraints get constraints => const BoxConstraints( + minWidth: 36.0, + minHeight: 36.0, + ); } class _LinearProgressIndicatorDefaultsM2 extends ProgressIndicatorThemeData { @@ -1200,6 +1362,29 @@ class _LinearProgressIndicatorDefaultsM2 extends ProgressIndicatorThemeData { double get linearMinHeight => 4.0; } +class _CircularProgressIndicatorDefaultsM3Year2023 extends ProgressIndicatorThemeData { + _CircularProgressIndicatorDefaultsM3Year2023(this.context, { required this.indeterminate }); + + final BuildContext context; + late final ColorScheme _colors = Theme.of(context).colorScheme; + final bool indeterminate; + + @override + Color get color => _colors.primary; + + @override + double get strokeWidth => 4.0; + + @override + double? get strokeAlign => CircularProgressIndicator.strokeAlignCenter; + + @override + BoxConstraints get constraints => const BoxConstraints( + minWidth: 36.0, + minHeight: 36.0, + ); +} + class _LinearProgressIndicatorDefaultsM3Year2023 extends ProgressIndicatorThemeData { _LinearProgressIndicatorDefaultsM3Year2023(this.context); @@ -1224,16 +1409,35 @@ class _LinearProgressIndicatorDefaultsM3Year2023 extends ProgressIndicatorThemeD // dev/tools/gen_defaults/bin/gen_defaults.dart. class _CircularProgressIndicatorDefaultsM3 extends ProgressIndicatorThemeData { - _CircularProgressIndicatorDefaultsM3(this.context); + _CircularProgressIndicatorDefaultsM3(this.context, { required this.indeterminate }); final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; + final bool indeterminate; @override Color get color => _colors.primary; @override - Color get circularTrackColor => _colors.secondaryContainer; + Color? get circularTrackColor => indeterminate ? null : _colors.secondaryContainer; + + @override + double get strokeWidth => 4.0; + + @override + double? get strokeAlign => CircularProgressIndicator.strokeAlignInside; + + @override + BoxConstraints get constraints => const BoxConstraints( + minWidth: 40.0, + minHeight: 40.0, + ); + + @override + double? get trackGap => 4.0; + + @override + EdgeInsetsGeometry? get circularTrackPadding => const EdgeInsets.all(4.0); } class _LinearProgressIndicatorDefaultsM3 extends ProgressIndicatorThemeData { diff --git a/packages/flutter/lib/src/material/progress_indicator_theme.dart b/packages/flutter/lib/src/material/progress_indicator_theme.dart index f93cd215e10..7a4c415f58c 100644 --- a/packages/flutter/lib/src/material/progress_indicator_theme.dart +++ b/packages/flutter/lib/src/material/progress_indicator_theme.dart @@ -42,7 +42,17 @@ class ProgressIndicatorThemeData with Diagnosticable { this.borderRadius, this.stopIndicatorColor, this.stopIndicatorRadius, + this.strokeWidth, + this.strokeAlign, + this.strokeCap, + this.constraints, this.trackGap, + this.circularTrackPadding, + @Deprecated( + 'Use ProgressIndicatorTheme to customize the ProgressIndicator appearance. ' + 'This feature was deprecated after v3.27.0-0.2.pre.' + ) + this.year2023, }); /// The color of the [ProgressIndicator]'s indicator. @@ -85,12 +95,47 @@ class ProgressIndicatorThemeData with Diagnosticable { /// is false, then no stop indicator will be drawn. final double? stopIndicatorRadius; - /// Overrides the gap between the [LinearProgressIndicator]. + /// Overrides the stroke width of the [CircularProgressIndicator]. + final double? strokeWidth; + + /// Overrides the stroke align of the [CircularProgressIndicator]. + final double? strokeAlign; + + /// Overrides the stroke cap of the [CircularProgressIndicator]. + final StrokeCap? strokeCap; + + /// Overrides the constraints of the [CircularProgressIndicator]. + final BoxConstraints? constraints; + + /// Overrides the active indicator and the background track. + /// + /// If [CircularProgressIndicator.year2023] is false or [ThemeData.useMaterial3] + /// is false, then no track gap will be drawn. /// /// If [LinearProgressIndicator.year2023] is false or [ThemeData.useMaterial3] /// is false, then no track gap will be drawn. final double? trackGap; + /// Overrides the padding of the [CircularProgressIndicator]. + final EdgeInsetsGeometry? circularTrackPadding; + + /// Overrides the [CircularProgressIndicator.year2023] and + /// [LinearProgressIndicator.year2023] properties. + /// + /// When true, the [CircularProgressIndicator] and [LinearProgressIndicator] + /// will use the 2023 Material Design 3 appearance. Defaults to true. + /// + /// If this is set to false, the [CircularProgressIndicator] and + /// [LinearProgressIndicator] will use the latest Material Design 3 appearance, + /// which was introduced in December 2023. + /// + /// If [ThemeData.useMaterial3] is false, then this property is ignored. + @Deprecated( + 'Use ProgressIndicatorTheme to customize the ProgressIndicator appearance. ' + 'This feature was deprecated after v3.27.0-0.2.pre.' + ) + final bool? year2023; + /// Creates a copy of this object but with the given fields replaced with the /// new values. ProgressIndicatorThemeData copyWith({ @@ -102,7 +147,13 @@ class ProgressIndicatorThemeData with Diagnosticable { BorderRadiusGeometry? borderRadius, Color? stopIndicatorColor, double? stopIndicatorRadius, + double? strokeWidth, + double? strokeAlign, + StrokeCap? strokeCap, + BoxConstraints? constraints, double? trackGap, + EdgeInsetsGeometry? circularTrackPadding, + bool? year2023, }) { return ProgressIndicatorThemeData( color: color ?? this.color, @@ -113,7 +164,13 @@ class ProgressIndicatorThemeData with Diagnosticable { borderRadius : borderRadius ?? this.borderRadius, stopIndicatorColor : stopIndicatorColor ?? this.stopIndicatorColor, stopIndicatorRadius : stopIndicatorRadius ?? this.stopIndicatorRadius, + strokeWidth : strokeWidth ?? this.strokeWidth, + strokeAlign : strokeAlign ?? this.strokeAlign, + strokeCap : strokeCap ?? this.strokeCap, + constraints: constraints ?? this.constraints, trackGap : trackGap ?? this.trackGap, + circularTrackPadding: circularTrackPadding ?? this.circularTrackPadding, + year2023: year2023 ?? this.year2023, ); } @@ -133,7 +190,13 @@ class ProgressIndicatorThemeData with Diagnosticable { borderRadius : BorderRadiusGeometry.lerp(a?.borderRadius, b?.borderRadius, t), stopIndicatorColor : Color.lerp(a?.stopIndicatorColor, b?.stopIndicatorColor, t), stopIndicatorRadius : lerpDouble(a?.stopIndicatorRadius, b?.stopIndicatorRadius, t), + strokeWidth : lerpDouble(a?.strokeWidth, b?.strokeWidth, t), + strokeAlign : lerpDouble(a?.strokeAlign, b?.strokeAlign, t), + strokeCap : t < 0.5 ? a?.strokeCap : b?.strokeCap, + constraints: BoxConstraints.lerp(a?.constraints, b?.constraints, t), trackGap : lerpDouble(a?.trackGap, b?.trackGap, t), + circularTrackPadding: EdgeInsetsGeometry.lerp(a?.circularTrackPadding, b?.circularTrackPadding, t), + year2023: t < 0.5 ? a?.year2023 : b?.year2023, ); } @@ -147,7 +210,13 @@ class ProgressIndicatorThemeData with Diagnosticable { borderRadius, stopIndicatorColor, stopIndicatorRadius, + strokeAlign, + strokeWidth, + strokeCap, + constraints, trackGap, + circularTrackPadding, + year2023, ); @override @@ -167,7 +236,13 @@ class ProgressIndicatorThemeData with Diagnosticable { && other.borderRadius == borderRadius && other.stopIndicatorColor == stopIndicatorColor && other.stopIndicatorRadius == stopIndicatorRadius - && other.trackGap == trackGap; + && other.strokeAlign == strokeAlign + && other.strokeWidth == strokeWidth + && other.strokeCap == strokeCap + && other.constraints == constraints + && other.trackGap == trackGap + && other.circularTrackPadding == circularTrackPadding + && other.year2023 == year2023; } @override @@ -181,7 +256,13 @@ class ProgressIndicatorThemeData with Diagnosticable { properties.add(DiagnosticsProperty('borderRadius', borderRadius, defaultValue: null)); properties.add(ColorProperty('stopIndicatorColor', stopIndicatorColor, defaultValue: null)); properties.add(DoubleProperty('stopIndicatorRadius', stopIndicatorRadius, defaultValue: null)); + properties.add(DoubleProperty('strokeWidth', strokeWidth, defaultValue: null)); + properties.add(DoubleProperty('strokeAlign', strokeAlign, defaultValue: null)); + properties.add(DiagnosticsProperty('strokeCap', strokeCap, defaultValue: null)); + properties.add(DiagnosticsProperty('constraints', constraints, defaultValue: null)); properties.add(DoubleProperty('trackGap', trackGap, defaultValue: null)); + properties.add(DiagnosticsProperty('circularTrackPadding', circularTrackPadding, defaultValue: null)); + properties.add(DiagnosticsProperty('year2023', year2023, defaultValue: null)); } } diff --git a/packages/flutter/lib/src/material/range_slider.dart b/packages/flutter/lib/src/material/range_slider.dart index 067f011d41d..29ae62f0a60 100644 --- a/packages/flutter/lib/src/material/range_slider.dart +++ b/packages/flutter/lib/src/material/range_slider.dart @@ -1402,8 +1402,32 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix sliderTheme: _sliderTheme, isDiscrete: isDiscrete, ); - _startThumbCenter = Offset(trackRect.left + startVisualPosition * trackRect.width, trackRect.center.dy); - _endThumbCenter = Offset(trackRect.left + endVisualPosition * trackRect.width, trackRect.center.dy); + final double padding = isDiscrete || _sliderTheme.rangeTrackShape!.isRounded ? trackRect.height : 0.0; + final double thumbYOffset = trackRect.center.dy; + final double startThumbPosition = isDiscrete + ? trackRect.left + startVisualPosition * (trackRect.width - padding) + padding / 2 + : trackRect.left + startVisualPosition * trackRect.width; + final double endThumbPosition = isDiscrete + ? trackRect.left + endVisualPosition * (trackRect.width - padding) + padding / 2 + : trackRect.left + endVisualPosition * trackRect.width; + final Size thumbPreferredSize = _sliderTheme.rangeThumbShape!.getPreferredSize(isEnabled, isDiscrete); + final double thumbPadding = (padding > thumbPreferredSize.width / 2 ? padding / 2 : 0); + _startThumbCenter = Offset( + clampDouble( + startThumbPosition, + trackRect.left + thumbPadding, + trackRect.right - thumbPadding, + ), + thumbYOffset, + ); + _endThumbCenter = Offset( + clampDouble( + endThumbPosition, + trackRect.left + thumbPadding, + trackRect.right - thumbPadding, + ), + thumbYOffset, + ); if (isEnabled) { final Size overlaySize = sliderTheme.overlayShape!.getPreferredSize(isEnabled, false); overlayStartRect = Rect.fromCircle(center: _startThumbCenter, radius: overlaySize.width / 2.0); @@ -1766,7 +1790,6 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix } } - class _ValueIndicatorRenderObjectWidget extends LeafRenderObjectWidget { const _ValueIndicatorRenderObjectWidget({ required this.state, diff --git a/packages/flutter/lib/src/material/refresh_indicator.dart b/packages/flutter/lib/src/material/refresh_indicator.dart index b26427d41c5..4949f063ccc 100644 --- a/packages/flutter/lib/src/material/refresh_indicator.dart +++ b/packages/flutter/lib/src/material/refresh_indicator.dart @@ -352,6 +352,7 @@ class RefreshIndicatorState extends State end: 0.0, ); + @protected @override void initState() { super.initState(); @@ -365,12 +366,14 @@ class RefreshIndicatorState extends State _scaleFactor = _scaleController.drive(_oneToZeroTween); } + @protected @override void didChangeDependencies() { _setupColorTween(); super.didChangeDependencies(); } + @protected @override void didUpdateWidget(covariant RefreshIndicator oldWidget) { super.didUpdateWidget(oldWidget); @@ -379,6 +382,7 @@ class RefreshIndicatorState extends State } } + @protected @override void dispose() { _positionController.dispose(); @@ -636,6 +640,7 @@ class RefreshIndicatorState extends State return _pendingRefreshFuture; } + @protected @override Widget build(BuildContext context) { assert(debugCheckHasMaterialLocalizations(context)); diff --git a/packages/flutter/lib/src/material/reorderable_list.dart b/packages/flutter/lib/src/material/reorderable_list.dart index 9c851ee581d..7c6f57920eb 100644 --- a/packages/flutter/lib/src/material/reorderable_list.dart +++ b/packages/flutter/lib/src/material/reorderable_list.dart @@ -102,6 +102,7 @@ class ReorderableListView extends StatefulWidget { this.restorationId, this.clipBehavior = Clip.hardEdge, this.autoScrollerVelocityScalar, + this.dragBoundaryProvider, }) : assert( (itemExtent == null && prototypeItem == null) || (itemExtent == null && itemExtentBuilder == null) || @@ -171,6 +172,7 @@ class ReorderableListView extends StatefulWidget { this.restorationId, this.clipBehavior = Clip.hardEdge, this.autoScrollerVelocityScalar, + this.dragBoundaryProvider, }) : assert(itemCount >= 0), assert( (itemExtent == null && prototypeItem == null) || @@ -292,6 +294,9 @@ class ReorderableListView extends StatefulWidget { /// {@macro flutter.widgets.SliverReorderableList.autoScrollerVelocityScalar.default} final double? autoScrollerVelocityScalar; + /// {@macro flutter.widgets.reorderable_list.dragBoundaryProvider} + final ReorderDragBoundaryProvider? dragBoundaryProvider; + @override State createState() => _ReorderableListViewState(); } @@ -446,6 +451,7 @@ class _ReorderableListViewState extends State { onReorderEnd: widget.onReorderEnd, proxyDecorator: widget.proxyDecorator ?? _proxyDecorator, autoScrollerVelocityScalar: widget.autoScrollerVelocityScalar, + dragBoundaryProvider: widget.dragBoundaryProvider, ), ), if (widget.footer != null) diff --git a/packages/flutter/lib/src/material/scaffold.dart b/packages/flutter/lib/src/material/scaffold.dart index 844370f414d..70ea06f3ef5 100644 --- a/packages/flutter/lib/src/material/scaffold.dart +++ b/packages/flutter/lib/src/material/scaffold.dart @@ -197,6 +197,7 @@ class ScaffoldMessengerState extends State with TickerProvide Timer? _snackBarTimer; bool? _accessibleNavigation; + @protected @override void didChangeDependencies() { final bool accessibleNavigation = MediaQuery.accessibleNavigationOf(context); @@ -604,6 +605,7 @@ class ScaffoldMessengerState extends State with TickerProvide hideCurrentMaterialBanner(); } + @protected @override Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); @@ -632,6 +634,7 @@ class ScaffoldMessengerState extends State with TickerProvide ); } + @protected @override void dispose() { _materialBannerController?.dispose(); @@ -2116,6 +2119,7 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto @override String? get restorationId => widget.restorationId; + @protected @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(_drawerOpened, 'drawer_open'); @@ -2676,6 +2680,7 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto return widget.resizeToAvoidBottomInset ?? true; } + @protected @override void initState() { super.initState(); @@ -2695,6 +2700,7 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto ); } + @protected @override void didUpdateWidget(Scaffold oldWidget) { super.didUpdateWidget(oldWidget); @@ -2732,6 +2738,7 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto } } + @protected @override void didChangeDependencies() { // Using maybeOf is valid here since both the Scaffold and ScaffoldMessenger @@ -2750,6 +2757,7 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto super.didChangeDependencies(); } + @protected @override void dispose() { _geometryNotifier.dispose(); @@ -2864,6 +2872,7 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto }); } + @protected @override Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); diff --git a/packages/flutter/lib/src/material/search_anchor.dart b/packages/flutter/lib/src/material/search_anchor.dart index 3cd1297fd45..2ebc5d65a31 100644 --- a/packages/flutter/lib/src/material/search_anchor.dart +++ b/packages/flutter/lib/src/material/search_anchor.dart @@ -6,6 +6,7 @@ import 'dart:async'; import 'dart:math' as math; import 'dart:ui'; +import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'adaptive_text_selection_toolbar.dart'; @@ -133,6 +134,7 @@ class SearchAnchor extends StatefulWidget { this.dividerColor, this.viewConstraints, this.viewPadding, + this.shrinkWrap, this.textCapitalization, this.viewOnChanged, this.viewOnSubmitted, @@ -170,6 +172,7 @@ class SearchAnchor extends StatefulWidget { EdgeInsetsGeometry? viewBarPadding, MaterialStateProperty? barTextStyle, MaterialStateProperty? barHintStyle, + ViewBuilder? viewBuilder, Widget? viewLeading, Iterable? viewTrailing, String? viewHintText, @@ -184,6 +187,7 @@ class SearchAnchor extends StatefulWidget { BoxConstraints? constraints, BoxConstraints? viewConstraints, EdgeInsetsGeometry? viewPadding, + bool? shrinkWrap, bool? isFullScreen, SearchController searchController, TextCapitalization textCapitalization, @@ -328,6 +332,14 @@ class SearchAnchor extends StatefulWidget { /// If null, the value of [SearchViewThemeData.padding] will be used. final EdgeInsetsGeometry? viewPadding; + /// Whether the search view should shrink-wrap its contents. + /// + /// Has no effect if the search view is full-screen. + /// + /// If null, the value of [SearchViewThemeData.shrinkWrap] will be used. If + /// this is also null, then the default value is `false`. + final bool? shrinkWrap; + /// {@macro flutter.widgets.editableText.textCapitalization} final TextCapitalization? textCapitalization; @@ -454,6 +466,7 @@ class _SearchAnchorState extends State { dividerColor: widget.dividerColor, viewConstraints: widget.viewConstraints, viewPadding: widget.viewPadding, + shrinkWrap: widget.shrinkWrap, showFullScreenView: getShowFullScreenView(), toggleVisibility: toggleVisibility, textDirection: Directionality.of(context), @@ -536,6 +549,7 @@ class _SearchViewRoute extends PopupRoute<_SearchViewRoute> { this.dividerColor, this.viewConstraints, this.viewPadding, + this.shrinkWrap, this.textCapitalization, required this.showFullScreenView, required this.anchorKey, @@ -566,6 +580,7 @@ class _SearchViewRoute extends PopupRoute<_SearchViewRoute> { final Color? dividerColor; final BoxConstraints? viewConstraints; final EdgeInsetsGeometry? viewPadding; + final bool? shrinkWrap; final TextCapitalization? textCapitalization; final bool showFullScreenView; final GlobalKey anchorKey; @@ -690,7 +705,6 @@ class _SearchViewRoute extends PopupRoute<_SearchViewRoute> { @override Widget buildPage(BuildContext context, Animation animation, Animation secondaryAnimation) { - return Directionality( textDirection: textDirection ?? TextDirection.ltr, child: AnimatedBuilder( @@ -732,7 +746,9 @@ class _SearchViewRoute extends PopupRoute<_SearchViewRoute> { viewHeaderTextStyle: viewHeaderTextStyle, viewHeaderHintStyle: viewHeaderHintStyle, dividerColor: dividerColor, + viewConstraints: viewConstraints, viewPadding: viewPadding, + shrinkWrap: shrinkWrap, showFullScreenView: showFullScreenView, animation: curvedAnimation!, topPadding: topPadding, @@ -774,7 +790,9 @@ class _ViewContent extends StatefulWidget { this.viewHeaderTextStyle, this.viewHeaderHintStyle, this.dividerColor, + this.viewConstraints, this.viewPadding, + this.shrinkWrap, this.textCapitalization, required this.showFullScreenView, required this.topPadding, @@ -803,7 +821,9 @@ class _ViewContent extends StatefulWidget { final TextStyle? viewHeaderTextStyle; final TextStyle? viewHeaderHintStyle; final Color? dividerColor; + final BoxConstraints? viewConstraints; final EdgeInsetsGeometry? viewPadding; + final bool? shrinkWrap; final TextCapitalization? textCapitalization; final bool showFullScreenView; final double topPadding; @@ -911,19 +931,6 @@ class _ViewContentState extends State<_ViewContent> { viewListFadeOnIntervalCurve.dispose(); } - Widget viewBuilder(Iterable suggestions) { - if (widget.viewBuilder == null) { - return MediaQuery.removePadding( - context: context, - removeTop: true, - child: ListView( - children: suggestions.toList() - ), - ); - } - return widget.viewBuilder!(suggestions); - } - Future updateSuggestions() async { if (searchValue != _controller.text) { searchValue = _controller.text; @@ -998,6 +1005,16 @@ class _ViewContentState extends State<_ViewContent> { ?? viewTheme.barPadding ?? viewDefaults.barPadding; + final BoxConstraints effectiveConstraints = widget.viewConstraints + ?? viewTheme.constraints + ?? viewDefaults.constraints!; + final double minWidth = math.min(effectiveConstraints.minWidth, _viewRect.width); + final double minHeight = math.min(effectiveConstraints.minHeight, _viewRect.height); + + final bool effectiveShrinkWrap = widget.shrinkWrap + ?? viewTheme.shrinkWrap + ?? viewDefaults.shrinkWrap!; + final Widget viewDivider = DividerTheme( data: dividerTheme.copyWith(color: effectiveDividerColor), child: const Divider(height: 1), @@ -1007,9 +1024,13 @@ class _ViewContentState extends State<_ViewContent> { alignment: Alignment.topLeft, child: Transform.translate( offset: _viewRect.topLeft, - child: SizedBox( - width: _viewRect.width, - height: _viewRect.height, + child: ConstrainedBox( + constraints: BoxConstraints( + minWidth: minWidth, + maxWidth: _viewRect.width, + minHeight: minHeight, + maxHeight: _viewRect.height, + ), child: Padding( padding: widget.showFullScreenView ? EdgeInsets.zero : (effectivePadding ?? EdgeInsets.zero), child: Material( @@ -1018,57 +1039,69 @@ class _ViewContentState extends State<_ViewContent> { color: effectiveBackgroundColor, surfaceTintColor: effectiveSurfaceTint, elevation: effectiveElevation, - child: ClipRect( - clipBehavior: Clip.antiAlias, - child: OverflowBox( - alignment: Alignment.topLeft, - maxWidth: math.min(widget.viewMaxWidth, _screenSize!.width), - minWidth: 0, - child: FadeTransition( - opacity: viewIconsFadeCurve, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Padding( - padding: EdgeInsets.only(top: widget.topPadding), - child: SafeArea( - top: false, - bottom: false, - child: SearchBar( - autoFocus: true, - constraints: headerConstraints ?? (widget.showFullScreenView ? BoxConstraints(minHeight: _SearchViewDefaultsM3.fullScreenBarHeight) : null), - padding: WidgetStatePropertyAll(effectiveBarPadding), - leading: widget.viewLeading ?? defaultLeading, - trailing: widget.viewTrailing ?? defaultTrailing, - hintText: widget.viewHintText, - backgroundColor: const MaterialStatePropertyAll(Colors.transparent), - overlayColor: const MaterialStatePropertyAll(Colors.transparent), - elevation: const MaterialStatePropertyAll(0.0), - textStyle: MaterialStatePropertyAll(effectiveTextStyle), - hintStyle: MaterialStatePropertyAll(effectiveHintStyle), - controller: _controller, - onChanged: (String value) { - widget.viewOnChanged?.call(value); - updateSuggestions(); - }, - onSubmitted: widget.viewOnSubmitted, - textCapitalization: widget.textCapitalization, - textInputAction: widget.textInputAction, - keyboardType: widget.keyboardType, - ), + child: OverflowBox( + alignment: Alignment.topLeft, + maxWidth: math.min(widget.viewMaxWidth, _screenSize!.width), + minWidth: 0, + fit: OverflowBoxFit.deferToChild, + child: FadeTransition( + opacity: viewIconsFadeCurve, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: EdgeInsets.only(top: widget.topPadding), + child: SafeArea( + top: false, + bottom: false, + child: SearchBar( + autoFocus: true, + constraints: headerConstraints ?? (widget.showFullScreenView ? BoxConstraints(minHeight: _SearchViewDefaultsM3.fullScreenBarHeight) : null), + padding: WidgetStatePropertyAll(effectiveBarPadding), + leading: widget.viewLeading ?? defaultLeading, + trailing: widget.viewTrailing ?? defaultTrailing, + hintText: widget.viewHintText, + backgroundColor: const MaterialStatePropertyAll(Colors.transparent), + overlayColor: const MaterialStatePropertyAll(Colors.transparent), + elevation: const MaterialStatePropertyAll(0.0), + textStyle: MaterialStatePropertyAll(effectiveTextStyle), + hintStyle: MaterialStatePropertyAll(effectiveHintStyle), + controller: _controller, + onChanged: (String value) { + widget.viewOnChanged?.call(value); + updateSuggestions(); + }, + onSubmitted: widget.viewOnSubmitted, + textCapitalization: widget.textCapitalization, + textInputAction: widget.textInputAction, + keyboardType: widget.keyboardType, ), ), + ), + if (!effectiveShrinkWrap || minHeight > 0 || widget.showFullScreenView || result.isNotEmpty) ...[ FadeTransition( opacity: viewDividerFadeCurve, - child: viewDivider), - Expanded( + child: viewDivider, + ), + Flexible( + fit: (effectiveShrinkWrap && !widget.showFullScreenView) ? FlexFit.loose : FlexFit.tight, child: FadeTransition( opacity: viewListFadeOnIntervalCurve, - child: viewBuilder(result), + child: widget.viewBuilder == null + ? MediaQuery.removePadding( + context: context, + removeTop: true, + child: ListView( + shrinkWrap: effectiveShrinkWrap, + children: result.toList(), + ), + ) + : widget.viewBuilder!(result), ), ), ], - ), + ], ), ), ), @@ -1095,6 +1128,7 @@ class _SearchAnchorWithSearchBar extends SearchAnchor { super.viewBarPadding, MaterialStateProperty? barTextStyle, MaterialStateProperty? barHintStyle, + super.viewBuilder, super.viewLeading, super.viewTrailing, String? viewHintText, @@ -1109,6 +1143,7 @@ class _SearchAnchorWithSearchBar extends SearchAnchor { BoxConstraints? constraints, super.viewConstraints, super.viewPadding, + super.shrinkWrap, super.isFullScreen, super.searchController, super.textCapitalization, @@ -1716,6 +1751,9 @@ class _SearchViewDefaultsM3 extends SearchViewThemeData { @override EdgeInsetsGeometry? get barPadding => const EdgeInsets.symmetric(horizontal: 8.0); + @override + bool get shrinkWrap => false; + @override Color? get dividerColor => _colors.outline; } diff --git a/packages/flutter/lib/src/material/search_view_theme.dart b/packages/flutter/lib/src/material/search_view_theme.dart index 125e414b882..877f389f766 100644 --- a/packages/flutter/lib/src/material/search_view_theme.dart +++ b/packages/flutter/lib/src/material/search_view_theme.dart @@ -46,6 +46,7 @@ class SearchViewThemeData with Diagnosticable { this.constraints, this.padding, this.barPadding, + this.shrinkWrap, this.side, this.shape, this.headerHeight, @@ -87,6 +88,9 @@ class SearchViewThemeData with Diagnosticable { /// Overrides the value of the padding for [SearchAnchor.viewBarPadding] final EdgeInsetsGeometry? barPadding; + /// Overrides the value of the shrink wrap for [SearchAnchor.shrinkWrap]. + final bool? shrinkWrap; + /// Overrides the value of the divider color for [SearchAnchor.dividerColor]. final Color? dividerColor; @@ -104,6 +108,7 @@ class SearchViewThemeData with Diagnosticable { BoxConstraints? constraints, EdgeInsetsGeometry? padding, EdgeInsetsGeometry? barPadding, + bool? shrinkWrap, Color? dividerColor, }) { return SearchViewThemeData( @@ -118,6 +123,7 @@ class SearchViewThemeData with Diagnosticable { constraints: constraints ?? this.constraints, padding: padding ?? this.padding, barPadding: barPadding ?? this.barPadding, + shrinkWrap: shrinkWrap ?? this.shrinkWrap, dividerColor: dividerColor ?? this.dividerColor, ); } @@ -139,6 +145,7 @@ class SearchViewThemeData with Diagnosticable { constraints: BoxConstraints.lerp(a?.constraints, b?.constraints, t), padding: EdgeInsetsGeometry.lerp(a?.padding, b?.padding, t), barPadding: EdgeInsetsGeometry.lerp(a?.barPadding, b?.barPadding, t), + shrinkWrap: t < 0.5 ? a?.shrinkWrap : b?.shrinkWrap, dividerColor: Color.lerp(a?.dividerColor, b?.dividerColor, t), ); } @@ -156,6 +163,7 @@ class SearchViewThemeData with Diagnosticable { constraints, padding, barPadding, + shrinkWrap, dividerColor, ); @@ -179,6 +187,7 @@ class SearchViewThemeData with Diagnosticable { && other.constraints == constraints && other.padding == padding && other.barPadding == barPadding + && other.shrinkWrap == shrinkWrap && other.dividerColor == dividerColor; } @@ -196,6 +205,7 @@ class SearchViewThemeData with Diagnosticable { properties.add(DiagnosticsProperty('constraints', constraints, defaultValue: null)); properties.add(DiagnosticsProperty('padding', padding, defaultValue: null)); properties.add(DiagnosticsProperty('barPadding', barPadding, defaultValue: null)); + properties.add(DiagnosticsProperty('shrinkWrap', shrinkWrap, defaultValue: null)); properties.add(DiagnosticsProperty('dividerColor', dividerColor, defaultValue: null)); } diff --git a/packages/flutter/lib/src/material/segmented_button.dart b/packages/flutter/lib/src/material/segmented_button.dart index 322f3c14979..0851dabfc62 100644 --- a/packages/flutter/lib/src/material/segmented_button.dart +++ b/packages/flutter/lib/src/material/segmented_button.dart @@ -426,6 +426,7 @@ class SegmentedButtonState extends State> { @visibleForTesting final Map, MaterialStatesController> statesControllers = , MaterialStatesController>{}; + @protected @override void didUpdateWidget(covariant SegmentedButton oldWidget) { super.didUpdateWidget(oldWidget); @@ -464,6 +465,7 @@ class SegmentedButtonState extends State> { } } + @protected @override Widget build(BuildContext context) { final SegmentedButtonThemeData theme = SegmentedButtonTheme.of(context); @@ -605,6 +607,7 @@ class SegmentedButtonState extends State> { ); } + @protected @override void dispose() { for (final MaterialStatesController controller in statesControllers.values) { diff --git a/packages/flutter/lib/src/material/selectable_text.dart b/packages/flutter/lib/src/material/selectable_text.dart index d432ce4d7fa..44cf398a65a 100644 --- a/packages/flutter/lib/src/material/selectable_text.dart +++ b/packages/flutter/lib/src/material/selectable_text.dart @@ -190,6 +190,7 @@ class SelectableText extends StatefulWidget { this.selectionControls, this.onTap, this.scrollPhysics, + this.scrollBehavior, this.semanticsLabel, this.textHeightBehavior, this.textWidthBasis, @@ -247,6 +248,7 @@ class SelectableText extends StatefulWidget { this.selectionControls, this.onTap, this.scrollPhysics, + this.scrollBehavior, this.semanticsLabel, this.textHeightBehavior, this.textWidthBasis, @@ -412,6 +414,9 @@ class SelectableText extends StatefulWidget { /// {@macro flutter.widgets.editableText.scrollPhysics} final ScrollPhysics? scrollPhysics; + /// {@macro flutter.widgets.editableText.scrollBehavior} + final ScrollBehavior? scrollBehavior; + /// {@macro flutter.widgets.Text.semanticsLabel} final String? semanticsLabel; @@ -467,6 +472,7 @@ class SelectableText extends StatefulWidget { properties.add(FlagProperty('selectionEnabled', value: selectionEnabled, defaultValue: true, ifFalse: 'selection disabled')); properties.add(DiagnosticsProperty('selectionControls', selectionControls, defaultValue: null)); properties.add(DiagnosticsProperty('scrollPhysics', scrollPhysics, defaultValue: null)); + properties.add(DiagnosticsProperty('scrollBehavior', scrollBehavior, defaultValue: null)); properties.add(DiagnosticsProperty('textHeightBehavior', textHeightBehavior, defaultValue: null)); } } @@ -738,6 +744,7 @@ class _SelectableTextState extends State implements TextSelectio magnifierConfiguration: widget.magnifierConfiguration ?? TextMagnifier.adaptiveMagnifierConfiguration, dragStartBehavior: widget.dragStartBehavior, scrollPhysics: widget.scrollPhysics, + scrollBehavior: widget.scrollBehavior, autofillHints: null, contextMenuBuilder: widget.contextMenuBuilder, ), diff --git a/packages/flutter/lib/src/material/selection_area.dart b/packages/flutter/lib/src/material/selection_area.dart index 5d305589c57..e1158a470fd 100644 --- a/packages/flutter/lib/src/material/selection_area.dart +++ b/packages/flutter/lib/src/material/selection_area.dart @@ -41,6 +41,8 @@ import 'theme.dart'; /// /// * [SelectableRegion], which provides an overview of the selection system. /// * [SelectableText], which enables selection on a single run of text. +/// * [SelectionListener], which enables accessing the [SelectionDetails] of +/// the selectable subtree it wraps. class SelectionArea extends StatefulWidget { /// Creates a [SelectionArea]. /// @@ -109,18 +111,11 @@ class SelectionArea extends StatefulWidget { /// State for a [SelectionArea]. class SelectionAreaState extends State { - FocusNode get _effectiveFocusNode => widget.focusNode ?? (_internalNode ??= FocusNode()); - FocusNode? _internalNode; final GlobalKey _selectableRegionKey = GlobalKey(); /// The [State] of the [SelectableRegion] for which this [SelectionArea] wraps. SelectableRegionState get selectableRegion => _selectableRegionKey.currentState!; - @override - void dispose() { - _internalNode?.dispose(); - super.dispose(); - } - + @protected @override Widget build(BuildContext context) { assert(debugCheckHasMaterialLocalizations(context)); @@ -133,7 +128,7 @@ class SelectionAreaState extends State { return SelectableRegion( key: _selectableRegionKey, selectionControls: controls, - focusNode: _effectiveFocusNode, + focusNode: widget.focusNode, contextMenuBuilder: widget.contextMenuBuilder, magnifierConfiguration: widget.magnifierConfiguration ?? TextMagnifier.adaptiveMagnifierConfiguration, onSelectionChanged: widget.onSelectionChanged, diff --git a/packages/flutter/lib/src/material/slider.dart b/packages/flutter/lib/src/material/slider.dart index c666e1d5407..3ac23cbe36a 100644 --- a/packages/flutter/lib/src/material/slider.dart +++ b/packages/flutter/lib/src/material/slider.dart @@ -78,27 +78,18 @@ enum SliderInteraction { /// {@youtube 560 315 https://www.youtube.com/watch?v=ufb4gIPDmEs} /// /// {@tool dartpad} -/// ![A legacy slider widget, consisting of 5 divisions and showing the default value -/// indicator.](https://flutter.github.io/assets-for-api-docs/assets/material/slider.png) -/// -/// The Sliders value is part of the Stateful widget subclass to change the value -/// setState was called. +/// This example showcases non-discrete and discrete [Slider]s. +/// The [Slider]s will show the updated ![Material 3 Design appearance](https://m3.material.io/components/sliders/overview) +/// when setting the [Slider.year2023] flag to false. /// /// ** See code in examples/api/lib/material/slider/slider.0.dart ** /// {@end-tool} /// /// {@tool dartpad} -/// This sample shows the creation of a [Slider] using [ThemeData.useMaterial3] flag, -/// as described in: https://m3.material.io/components/sliders/overview. -/// -/// ** See code in examples/api/lib/material/slider/slider.1.dart ** -/// {@end-tool} -/// -/// {@tool dartpad} /// This example shows a [Slider] widget using the [Slider.secondaryTrackValue] /// to show a secondary track in the slider. /// -/// ** See code in examples/api/lib/material/slider/slider.2.dart ** +/// ** See code in examples/api/lib/material/slider/slider.1.dart ** /// {@end-tool} /// /// A slider can be used to select from either a continuous or a discrete set of @@ -197,6 +188,11 @@ class Slider extends StatefulWidget { this.autofocus = false, this.allowedInteraction, this.padding, + @Deprecated( + 'Use SliderTheme to customize the Slider appearance. ' + 'This feature was deprecated after v3.27.0-0.1.pre.' + ) + this.year2023, }) : _sliderType = _SliderType.material, assert(min <= max), assert(value >= min && value <= max, @@ -238,6 +234,11 @@ class Slider extends StatefulWidget { this.focusNode, this.autofocus = false, this.allowedInteraction, + @Deprecated( + 'Use SliderTheme to customize the Slider appearance. ' + 'This feature was deprecated after v3.27.0-0.1.pre.' + ) + this.year2023, }) : _sliderType = _SliderType.adaptive, padding = null, assert(min <= max), @@ -432,9 +433,10 @@ class Slider extends StatefulWidget { /// maximum value. /// /// If null, [SliderThemeData.inactiveTrackColor] of the ambient [SliderTheme] - /// is used. If that is null and [ThemeData.useMaterial3] is true, - /// [ColorScheme.surfaceContainerHighest] will be used, otherwise [ColorScheme.primary] - /// with an opacity of 0.24 will be used. + /// is used. If [Slider.year2023] is false and [ThemeData.useMaterial3] is true, + /// then [ColorScheme.secondaryContainer] is used and if [ThemeData.useMaterial3] + /// is false, [ColorScheme.primary] with an opacity of 0.24 is used. Otherwise, + /// [ColorScheme.surfaceContainerHighest] is used. /// /// Using a [SliderTheme] gives much more fine-grained control over the /// appearance of various components of the slider. @@ -555,6 +557,19 @@ class Slider extends StatefulWidget { /// overlay shape, whichever is larger. final EdgeInsetsGeometry? padding; + /// When true, the [Slider] will use the 2023 Material Design 3 appearance. + /// Defaults to true. + /// + /// If this is set to false, the [Slider] will use the latest Material Design 3 + /// appearance, which was introduced in December 2023. + /// + /// If [ThemeData.useMaterial3] is false, then this property is ignored. + @Deprecated( + 'Use SliderTheme to customize the Slider appearance. ' + 'This feature was deprecated after v3.27.0-0.1.pre.' + ) + final bool? year2023; + final _SliderType _sliderType ; @override @@ -787,7 +802,13 @@ class _SliderState extends State with TickerProviderStateMixin { Widget _buildMaterialSlider(BuildContext context) { final ThemeData theme = Theme.of(context); SliderThemeData sliderTheme = SliderTheme.of(context); - final SliderThemeData defaults = theme.useMaterial3 ? _SliderDefaultsM3(context) : _SliderDefaultsM2(context); + final bool year2023 = widget.year2023 ?? sliderTheme.year2023 ?? true; + final SliderThemeData defaults = switch (theme.useMaterial3) { + true => year2023 + ? _SliderDefaultsM3Year2023(context) + : _SliderDefaultsM3(context), + false => _SliderDefaultsM2(context), + }; // If the widget has active or inactive colors specified, then we plug them // in to the slider theme as best we can. If the developer wants more @@ -796,11 +817,6 @@ class _SliderState extends State with TickerProviderStateMixin { // the default shapes and text styles are aligned to the Material // Guidelines. - const SliderTrackShape defaultTrackShape = RoundedRectSliderTrackShape(); - const SliderTickMarkShape defaultTickMarkShape = RoundSliderTickMarkShape(); - const SliderComponentShape defaultOverlayShape = RoundSliderOverlayShape(); - const SliderComponentShape defaultThumbShape = RoundSliderThumbShape(); - final SliderComponentShape defaultValueIndicatorShape = defaults.valueIndicatorShape!; const ShowValueIndicator defaultShowValueIndicator = ShowValueIndicator.onlyForDiscrete; const SliderInteraction defaultAllowedInteraction = SliderInteraction.tapAndSlide; @@ -815,12 +831,18 @@ class _SliderState extends State with TickerProviderStateMixin { // (which can be defined by activeColor) if the // RectangularSliderValueIndicatorShape is used. In all other cases, the // value indicator is assumed to be the same as the active color. - final SliderComponentShape valueIndicatorShape = sliderTheme.valueIndicatorShape ?? defaultValueIndicatorShape; + final SliderComponentShape valueIndicatorShape = sliderTheme.valueIndicatorShape ?? defaults.valueIndicatorShape!; final Color valueIndicatorColor; if (valueIndicatorShape is RectangularSliderValueIndicatorShape) { - valueIndicatorColor = sliderTheme.valueIndicatorColor ?? Color.alphaBlend(theme.colorScheme.onSurface.withOpacity(0.60), theme.colorScheme.surface.withOpacity(0.90)); + valueIndicatorColor = sliderTheme.valueIndicatorColor + ?? Color.alphaBlend( + theme.colorScheme.onSurface.withOpacity(0.60), + theme.colorScheme.surface.withOpacity(0.90), + ); } else { - valueIndicatorColor = widget.activeColor ?? sliderTheme.valueIndicatorColor ?? theme.colorScheme.primary; + valueIndicatorColor = widget.activeColor + ?? sliderTheme.valueIndicatorColor + ?? defaults.valueIndicatorColor!; } Color? effectiveOverlayColor() { @@ -851,14 +873,16 @@ class _SliderState extends State with TickerProviderStateMixin { disabledThumbColor: sliderTheme.disabledThumbColor ?? defaults.disabledThumbColor, overlayColor: effectiveOverlayColor(), valueIndicatorColor: valueIndicatorColor, - trackShape: sliderTheme.trackShape ?? defaultTrackShape, - tickMarkShape: sliderTheme.tickMarkShape ?? defaultTickMarkShape, - thumbShape: sliderTheme.thumbShape ?? defaultThumbShape, - overlayShape: sliderTheme.overlayShape ?? defaultOverlayShape, + trackShape: sliderTheme.trackShape ?? defaults.trackShape, + tickMarkShape: sliderTheme.tickMarkShape ?? defaults.tickMarkShape, + thumbShape: sliderTheme.thumbShape ?? defaults.thumbShape, + overlayShape: sliderTheme.overlayShape ?? defaults.overlayShape, valueIndicatorShape: valueIndicatorShape, showValueIndicator: sliderTheme.showValueIndicator ?? defaultShowValueIndicator, valueIndicatorTextStyle: valueIndicatorTextStyle, padding: widget.padding ?? sliderTheme.padding, + thumbSize: sliderTheme.thumbSize ?? defaults.thumbSize, + trackGap: sliderTheme.trackGap ?? defaults.trackGap, ); final MouseCursor effectiveMouseCursor = MaterialStateProperty.resolveAs(widget.mouseCursor, states) ?? sliderTheme.mouseCursor?.resolve(states) @@ -1683,8 +1707,8 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { : trackRect.left + visualPosition * trackRect.width; // Apply padding to trackRect.left and trackRect.right if the track height is // greater than the thumb radius to ensure the thumb is drawn within the track. - final Size thumbSize = _sliderTheme.thumbShape!.getPreferredSize(isInteractive, isDiscrete); - final double thumbPadding = (padding > thumbSize.width / 2 ? padding / 2 : 0); + final Size thumbPreferredSize = _sliderTheme.thumbShape!.getPreferredSize(isInteractive, isDiscrete); + final double thumbPadding = (padding > thumbPreferredSize.width / 2 ? padding / 2 : 0); final Offset thumbCenter = Offset( clampDouble( thumbPosition, @@ -1697,13 +1721,32 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { final Size overlaySize = sliderTheme.overlayShape!.getPreferredSize(isInteractive, false); overlayRect = Rect.fromCircle(center: thumbCenter, radius: overlaySize.width / 2.0); } - final Offset? secondaryOffset = (secondaryVisualPosition != null) ? Offset(trackRect.left + secondaryVisualPosition * trackRect.width, trackRect.center.dy) : null; + final Offset? secondaryOffset = (secondaryVisualPosition != null) + ? Offset(trackRect.left + secondaryVisualPosition * trackRect.width, trackRect.center.dy) + : null; + + // If [Slider.year2023] is false, the thumb uses handle thumb shape and gapped track shape. + // The handle width and track gap are adjusted when the thumb is pressed. + double? thumbWidth = _sliderTheme.thumbSize?.resolve({})?.width; + final double? thumbHeight = _sliderTheme.thumbSize?.resolve({})?.height; + double? trackGap = _sliderTheme.trackGap; + final double? pressedThumbWidth = _sliderTheme.thumbSize?.resolve({ MaterialState.pressed })?.width; + final double delta; + if (_active && thumbWidth != null && pressedThumbWidth != null && trackGap != null) { + delta = thumbWidth - pressedThumbWidth; + if (thumbWidth > 0.0) { + thumbWidth = pressedThumbWidth; + } + if (trackGap > 0.0) { + trackGap = trackGap - delta / 2; + } + } _sliderTheme.trackShape!.paint( context, offset, parentBox: this, - sliderTheme: _sliderTheme, + sliderTheme: _sliderTheme.copyWith(trackGap: trackGap), enableAnimation: _enableAnimation, textDirection: _textDirection, thumbCenter: thumbCenter, @@ -1789,7 +1832,9 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { isDiscrete: isDiscrete, labelPainter: _labelPainter, parentBox: this, - sliderTheme: _sliderTheme, + sliderTheme: thumbWidth != null && thumbHeight != null + ? _sliderTheme.copyWith(thumbSize: MaterialStatePropertyAll(Size(thumbWidth, thumbHeight))) + : _sliderTheme, textDirection: _textDirection, value: _value, textScaleFactor: textScaleFactor, @@ -1960,12 +2005,11 @@ class _RenderValueIndicator extends RenderBox with RelayoutWhenSystemFontsChange } class _SliderDefaultsM2 extends SliderThemeData { - _SliderDefaultsM2(this.context) - : _colors = Theme.of(context).colorScheme, - super(trackHeight: 4.0); + _SliderDefaultsM2(this.context) : super(trackHeight: 4.0); final BuildContext context; - final ColorScheme _colors; + late final ColorScheme _colors = Theme.of(context).colorScheme; + late final SliderThemeData sliderTheme = SliderTheme.of(context); @override Color? get activeTrackColor => _colors.primary; @@ -2011,20 +2055,32 @@ class _SliderDefaultsM2 extends SliderThemeData { color: _colors.onPrimary, ); + @override + Color? get valueIndicatorColor { + if (sliderTheme.valueIndicatorShape is RoundedRectSliderValueIndicatorShape) { + return _colors.inverseSurface; + } + return _colors.primary; + } + @override SliderComponentShape? get valueIndicatorShape => const RectangularSliderValueIndicatorShape(); + + @override + SliderComponentShape? get thumbShape => const RoundSliderThumbShape(); + + @override + SliderTrackShape? get trackShape => const RoundedRectSliderTrackShape(); + + @override + SliderComponentShape? get overlayShape => const RoundSliderOverlayShape(); + + @override + SliderTickMarkShape? get tickMarkShape => const RoundSliderTickMarkShape(); } -// TODO(quncheng): Update M3 defaults to match the latest specs. -// BEGIN GENERATED TOKEN PROPERTIES - Slider - -// Do not edit by hand. The code between the "BEGIN GENERATED" and -// "END GENERATED" comments are generated from data in the Material -// Design token database by the script: -// dev/tools/gen_defaults/bin/gen_defaults.dart. - -class _SliderDefaultsM3 extends SliderThemeData { - _SliderDefaultsM3(this.context) +class _SliderDefaultsM3Year2023 extends SliderThemeData { + _SliderDefaultsM3Year2023(this.context) : super(trackHeight: 4.0); final BuildContext context; @@ -2086,8 +2142,134 @@ class _SliderDefaultsM3 extends SliderThemeData { color: _colors.onPrimary, ); + @override + Color? get valueIndicatorColor => _colors.primary; + @override SliderComponentShape? get valueIndicatorShape => const DropSliderValueIndicatorShape(); + + @override + SliderComponentShape? get thumbShape => const RoundSliderThumbShape(); + + @override + SliderTrackShape? get trackShape => const RoundedRectSliderTrackShape(); + + @override + SliderComponentShape? get overlayShape => const RoundSliderOverlayShape(); + + @override + SliderTickMarkShape? get tickMarkShape => const RoundSliderTickMarkShape(); +} + +// BEGIN GENERATED TOKEN PROPERTIES - Slider + +// Do not edit by hand. The code between the "BEGIN GENERATED" and +// "END GENERATED" comments are generated from data in the Material +// Design token database by the script: +// dev/tools/gen_defaults/bin/gen_defaults.dart. + +class _SliderDefaultsM3 extends SliderThemeData { + _SliderDefaultsM3(this.context) + : super(trackHeight: 16.0); + + final BuildContext context; + late final ColorScheme _colors = Theme.of(context).colorScheme; + + @override + Color? get activeTrackColor => _colors.primary; + + @override + Color? get inactiveTrackColor => _colors.secondaryContainer; + + @override + Color? get secondaryActiveTrackColor => _colors.primary.withOpacity(0.54); + + @override + Color? get disabledActiveTrackColor => _colors.onSurface.withOpacity(0.38); + + @override + Color? get disabledInactiveTrackColor => _colors.onSurface.withOpacity(0.12); + + @override + Color? get disabledSecondaryActiveTrackColor => _colors.onSurface.withOpacity(0.38); + + @override + Color? get activeTickMarkColor => _colors.onPrimary.withOpacity(1.0); + + @override + Color? get inactiveTickMarkColor => _colors.onSecondaryContainer.withOpacity(1.0); + + @override + Color? get disabledActiveTickMarkColor => _colors.onInverseSurface; + + @override + Color? get disabledInactiveTickMarkColor => _colors.onSurface; + + @override + Color? get thumbColor => _colors.primary; + + @override + Color? get disabledThumbColor => _colors.onSurface.withOpacity(0.38); + + @override + Color? get overlayColor => MaterialStateColor.resolveWith((Set states) { + if (states.contains(MaterialState.dragged)) { + return _colors.primary.withOpacity(0.1); + } + if (states.contains(MaterialState.hovered)) { + return _colors.primary.withOpacity(0.08); + } + if (states.contains(MaterialState.focused)) { + return _colors.primary.withOpacity(0.1); + } + + return Colors.transparent; + }); + + @override + TextStyle? get valueIndicatorTextStyle => Theme.of(context).textTheme.labelLarge!.copyWith( + color: _colors.onInverseSurface, + ); + + @override + Color? get valueIndicatorColor => _colors.inverseSurface; + + @override + SliderComponentShape? get valueIndicatorShape => const RoundedRectSliderValueIndicatorShape(); + + @override + SliderComponentShape? get thumbShape => const HandleThumbShape(); + + @override + SliderTrackShape? get trackShape => const GappedSliderTrackShape(); + + @override + SliderComponentShape? get overlayShape => const RoundSliderOverlayShape(); + + @override + SliderTickMarkShape? get tickMarkShape => const RoundSliderTickMarkShape(tickMarkRadius: 4.0 / 2); + + @override + MaterialStateProperty? get thumbSize { + return MaterialStateProperty.resolveWith((Set states) { + if (states.contains(MaterialState.disabled)) { + return const Size(4.0, 44.0); + } + if (states.contains(MaterialState.hovered)) { + return const Size(4.0, 44.0); + } + if (states.contains(MaterialState.focused)) { + return const Size(2.0, 44.0); + } + if (states.contains(MaterialState.pressed)) { + return const Size(2.0, 44.0); + } + return const Size(4.0, 44.0); + }); + } + + @override + double? get trackGap => 6.0; } // END GENERATED TOKEN PROPERTIES - Slider diff --git a/packages/flutter/lib/src/material/slider_theme.dart b/packages/flutter/lib/src/material/slider_theme.dart index db1004076bd..f6e01833b27 100644 --- a/packages/flutter/lib/src/material/slider_theme.dart +++ b/packages/flutter/lib/src/material/slider_theme.dart @@ -297,6 +297,13 @@ class SliderThemeData with Diagnosticable { this.mouseCursor, this.allowedInteraction, this.padding, + this.thumbSize, + this.trackGap, + @Deprecated( + 'Use SliderTheme to customize the Slider appearance. ' + 'This feature was deprecated after v3.27.0-0.2.pre.' + ) + this.year2023, }); /// Generates a SliderThemeData from three main colors. @@ -597,6 +604,45 @@ class SliderThemeData with Diagnosticable { /// overlay shape, whichever is larger. final EdgeInsetsGeometry? padding; + /// The size of the [HandleThumbShape] thumb. + /// + /// If [SliderThemeData.thumbShape] is [HandleThumbShape], this property is used to + /// set the size of the thumb. Otherwise, the default thumb size is 4 pixels for the + /// width and 44 pixels for the height. + final MaterialStateProperty? thumbSize; + + /// The size of the gap between the active and inactive tracks of the [GappedSliderTrackShape]. + /// + /// If [SliderThemeData.trackShape] is [GappedSliderTrackShape], this property + /// is used to set the gap between the active and inactive tracks. Otherwise, + /// the default gap size is 6.0 pixels. + /// + /// The Slider defaults to [GappedSliderTrackShape] when the track shape is + /// not specified, and the [trackGap] can be used to adjust the gap size. + /// + /// If [Slider.year2023] is false or [ThemeData.useMaterial3] is false, then + /// the Slider track shape defaults to [RoundedRectSliderTrackShape] and the + /// [trackGap] is ignored. In this case, set the track shape to + /// [GappedSliderTrackShape] to use the [trackGap]. + /// + /// Defaults to 6.0 pixels of gap between the active and inactive tracks. + final double? trackGap; + + /// Overrides the default value of [Slider.year2023]. + /// + /// When true, the [Slider] will use the 2023 Material Design 3 appearance. + /// Defaults to true. + /// + /// If this is set to false, the [Slider] will use the latest Material Design 3 + /// appearance, which was introduced in December 2023. + /// + /// If [ThemeData.useMaterial3] is false, then this property is ignored. + @Deprecated( + 'Use SliderTheme to customize the Slider appearance. ' + 'This feature was deprecated after v3.27.0-0.2.pre.' + ) + final bool? year2023; + /// Creates a copy of this object but with the given fields replaced with the /// new values. SliderThemeData copyWith({ @@ -633,6 +679,9 @@ class SliderThemeData with Diagnosticable { MaterialStateProperty? mouseCursor, SliderInteraction? allowedInteraction, EdgeInsetsGeometry? padding, + MaterialStateProperty? thumbSize, + double? trackGap, + bool? year2023, }) { return SliderThemeData( trackHeight: trackHeight ?? this.trackHeight, @@ -668,6 +717,9 @@ class SliderThemeData with Diagnosticable { mouseCursor: mouseCursor ?? this.mouseCursor, allowedInteraction: allowedInteraction ?? this.allowedInteraction, padding: padding ?? this.padding, + thumbSize: thumbSize ?? this.thumbSize, + trackGap: trackGap ?? this.trackGap, + year2023: year2023 ?? this.year2023, ); } @@ -712,6 +764,9 @@ class SliderThemeData with Diagnosticable { mouseCursor: t < 0.5 ? a.mouseCursor : b.mouseCursor, allowedInteraction: t < 0.5 ? a.allowedInteraction : b.allowedInteraction, padding: EdgeInsetsGeometry.lerp(a.padding, b.padding, t), + thumbSize: MaterialStateProperty.lerp(a.thumbSize, b.thumbSize, t, Size.lerp), + trackGap: lerpDouble(a.trackGap, b.trackGap, t), + year2023: t < 0.5 ? a.year2023 : b.year2023, ); } @@ -750,6 +805,9 @@ class SliderThemeData with Diagnosticable { mouseCursor, allowedInteraction, padding, + thumbSize, + trackGap, + year2023, ), ); @@ -794,7 +852,10 @@ class SliderThemeData with Diagnosticable { && other.thumbSelector == thumbSelector && other.mouseCursor == mouseCursor && other.allowedInteraction == allowedInteraction - && other.padding == padding; + && other.padding == padding + && other.thumbSize == thumbSize + && other.trackGap == trackGap + && other.year2023 == year2023; } @override @@ -834,6 +895,9 @@ class SliderThemeData with Diagnosticable { properties.add(DiagnosticsProperty>('mouseCursor', mouseCursor, defaultValue: defaultData.mouseCursor)); properties.add(EnumProperty('allowedInteraction', allowedInteraction, defaultValue: defaultData.allowedInteraction)); properties.add(DiagnosticsProperty('padding', padding, defaultValue: defaultData.padding)); + properties.add(DiagnosticsProperty>('thumbSize', thumbSize, defaultValue: defaultData.thumbSize)); + properties.add(DoubleProperty('trackGap', trackGap, defaultValue: defaultData.trackGap)); + properties.add(DiagnosticsProperty('year2023', year2023, defaultValue: defaultData.year2023)); } } @@ -1512,6 +1576,10 @@ abstract class RangeSliderTrackShape { bool isDiscrete = false, required TextDirection textDirection, }); + + /// Whether the track shape is rounded. This is used to determine the correct + /// position of the thumbs in relation to the track. Defaults to false. + bool get isRounded => false; } /// Base track shape that provides an implementation of [getPreferredRect] for @@ -2042,15 +2110,6 @@ class RoundedRectRangeSliderTrackShape extends RangeSliderTrackShape with BaseRa ), inactivePaint, ); - context.canvas.drawRect( - Rect.fromLTRB( - leftThumbOffset.dx, - trackRect.top - (additionalActiveTrackHeight / 2), - rightThumbOffset.dx, - trackRect.bottom + (additionalActiveTrackHeight / 2), - ), - activePaint, - ); context.canvas.drawRRect( RRect.fromLTRBAndCorners( rightThumbOffset.dx, @@ -2062,7 +2121,20 @@ class RoundedRectRangeSliderTrackShape extends RangeSliderTrackShape with BaseRa ), inactivePaint, ); + context.canvas.drawRRect( + RRect.fromLTRBR( + leftThumbOffset.dx - (sliderTheme.trackHeight! / 2), + trackRect.top - (additionalActiveTrackHeight / 2), + rightThumbOffset.dx + (sliderTheme.trackHeight! / 2), + trackRect.bottom + (additionalActiveTrackHeight / 2), + trackRadius, + ), + activePaint, + ); } + + @override + bool get isRounded => true; } /// The default shape of each [Slider] tick mark. @@ -3559,3 +3631,457 @@ class _DropSliderValueIndicatorPathPainter { canvas.restore(); } } + +/// The bar shape of a [Slider]'s thumb. +/// +/// When the slider is enabled, the [ColorScheme.primary] color is used for the +/// thumb. When the slider is disabled, the [ColorScheme.onSurface] color with an +/// opacity of 0.38 is used for the thumb. +/// +/// The thumb bar shape width is reduced when the thumb is pressed. +/// +/// If [SliderThemeData.thumbSize] is null, then the thumb size is 4 pixels for the width +/// and 44 pixels for the height. +/// +/// This is the default thumb shape for [Slider]. If [ThemeData.useMaterial3] is false, +/// then the default thumb shape is [RoundSliderThumbShape]. +/// +/// See also: +/// +/// * [Slider], which includes an overlay defined by this shape. +/// * [SliderTheme], which can be used to configure the overlay shape of all +/// sliders in a widget subtree. +class HandleThumbShape extends SliderComponentShape { + /// Create a slider thumb that draws a bar. + const HandleThumbShape(); + + @override + Size getPreferredSize(bool isEnabled, bool isDiscrete) { + return const Size(4.0, 44.0); + } + + @override + void paint( + PaintingContext context, + Offset center, { + required Animation activationAnimation, + required Animation enableAnimation, + required bool isDiscrete, + required TextPainter labelPainter, + required RenderBox parentBox, + required SliderThemeData sliderTheme, + required TextDirection textDirection, + required double value, + required double textScaleFactor, + required Size sizeWithOverflow, + }) { + assert(sliderTheme.disabledThumbColor != null); + assert(sliderTheme.thumbColor != null); + assert(sliderTheme.thumbSize != null); + + final ColorTween colorTween = ColorTween( + begin: sliderTheme.disabledThumbColor, + end: sliderTheme.thumbColor, + ); + final Color color = colorTween.evaluate(enableAnimation)!; + + final Canvas canvas = context.canvas; + final Size thumbSize = sliderTheme.thumbSize!.resolve({})!; // This is resolved in the paint method. + final RRect rrect = RRect.fromRectAndRadius( + Rect.fromCenter( + center: center, + width: thumbSize.width, + height: thumbSize.height, + ), + Radius.circular(thumbSize.shortestSide / 2), + ); + canvas.drawRRect(rrect, Paint()..color = color); + } +} + +/// The gapped shape of a [Slider]'s track. +/// +/// The [GappedSliderTrackShape] consists of active and inactive +/// tracks. The active track uses the [SliderThemeData.activeTrackColor] and the +/// inactive track uses the [SliderThemeData.inactiveTrackColor]. +/// +/// The track shape uses circular corner radius for the edge corners and a corner radius +/// of 2 pixels for the inside corners. +/// +/// Between the active and inactive tracks there is a gap of size [SliderThemeData.trackGap]. +/// If the [SliderThemeData.thumbShape] is [HandleThumbShape] and the thumb is pressed, the thumb's +/// width is reduced; as a result, the track gap size in [GappedSliderTrackShape] +/// is also reduced. +/// +/// If [SliderThemeData.trackGap] is null, then the track gap size defaults to 6 pixels. +/// +/// This is the default track shape for [Slider]. If [ThemeData.useMaterial3] is false, +/// then the default track shape is [RoundedRectSliderTrackShape]. +/// +/// See also: +/// +/// * [Slider], which includes an overlay defined by this shape. +/// * [SliderTheme], which can be used to configure the overlay shape of all +/// sliders in a widget subtree. +class GappedSliderTrackShape extends SliderTrackShape with BaseSliderTrackShape { + /// Create a slider track that draws two rectangles with rounded outer edges. + const GappedSliderTrackShape(); + + @override + void paint( + PaintingContext context, + Offset offset, { + required RenderBox parentBox, + required SliderThemeData sliderTheme, + required Animation enableAnimation, + required TextDirection textDirection, + required Offset thumbCenter, + Offset? secondaryOffset, + bool isDiscrete = false, + bool isEnabled = false, + double additionalActiveTrackHeight = 2, + }) { + assert(sliderTheme.disabledActiveTrackColor != null); + assert(sliderTheme.disabledInactiveTrackColor != null); + assert(sliderTheme.activeTrackColor != null); + assert(sliderTheme.inactiveTrackColor != null); + assert(sliderTheme.thumbShape != null); + assert(sliderTheme.trackGap != null); + assert(!sliderTheme.trackGap!.isNegative); + // If the slider [SliderThemeData.trackHeight] is less than or equal to 0, + // then it makes no difference whether the track is painted or not, + // therefore the painting can be a no-op. + if (sliderTheme.trackHeight == null || sliderTheme.trackHeight! <= 0) { + return; + } + + // Assign the track segment paints, which are left: active, right: inactive, + // but reversed for right to left text. + final ColorTween activeTrackColorTween = ColorTween( + begin: sliderTheme.disabledActiveTrackColor, + end: sliderTheme.activeTrackColor, + ); + final ColorTween inactiveTrackColorTween = ColorTween( + begin: sliderTheme.disabledInactiveTrackColor, + end: sliderTheme.inactiveTrackColor, + ); + final Paint activePaint = Paint() + ..color = activeTrackColorTween.evaluate(enableAnimation)!; + final Paint inactivePaint = Paint() + ..color = inactiveTrackColorTween.evaluate(enableAnimation)!; + final Paint leftTrackPaint; + final Paint rightTrackPaint; + switch (textDirection) { + case TextDirection.ltr: + leftTrackPaint = activePaint; + rightTrackPaint = inactivePaint; + case TextDirection.rtl: + leftTrackPaint = inactivePaint; + rightTrackPaint = activePaint; + } + + // Gap, starting from the middle of the thumb. + final double trackGap = sliderTheme.trackGap!; + + final Rect trackRect = getPreferredRect( + parentBox: parentBox, + offset: offset, + sliderTheme: sliderTheme, + isEnabled: isEnabled, + isDiscrete: isDiscrete, + ); + + final Radius trackCornerRadius = Radius.circular(trackRect.shortestSide / 2); + const Radius trackInsideCornerRadius = Radius.circular(2.0); + + final RRect trackRRect = RRect.fromRectAndCorners( + trackRect, + topLeft: trackCornerRadius, + bottomLeft: trackCornerRadius, + topRight: trackCornerRadius, + bottomRight: trackCornerRadius, + ); + + final RRect leftRRect = RRect.fromLTRBAndCorners( + trackRect.left, + trackRect.top, + math.max(trackRect.left, thumbCenter.dx - trackGap), + trackRect.bottom, + topLeft: trackCornerRadius, + bottomLeft: trackCornerRadius, + topRight: trackInsideCornerRadius, + bottomRight: trackInsideCornerRadius, + ); + + final RRect rightRRect = RRect.fromLTRBAndCorners( + thumbCenter.dx + trackGap, + trackRect.top, + trackRect.right, + trackRect.bottom, + topRight: trackCornerRadius, + bottomRight: trackCornerRadius, + topLeft: trackInsideCornerRadius, + bottomLeft: trackInsideCornerRadius, + ); + + context.canvas..save()..clipRRect(trackRRect); + final bool drawLeftTrack = thumbCenter.dx > (leftRRect.left + (sliderTheme.trackHeight! / 2)); + final bool drawRightTrack = thumbCenter.dx < (rightRRect.right - (sliderTheme.trackHeight! / 2)); + if (drawLeftTrack) { + context.canvas.drawRRect(leftRRect, leftTrackPaint); + } + if (drawRightTrack) { + context.canvas.drawRRect(rightRRect, rightTrackPaint); + } + + final bool isLTR = textDirection == TextDirection.ltr; + final bool showSecondaryTrack = (secondaryOffset != null) && switch (isLTR) { + true => secondaryOffset.dx > thumbCenter.dx + trackGap, + false => secondaryOffset.dx < thumbCenter.dx - trackGap, + }; + + if (showSecondaryTrack) { + final ColorTween secondaryTrackColorTween = ColorTween(begin: sliderTheme.disabledSecondaryActiveTrackColor, end: sliderTheme.secondaryActiveTrackColor); + final Paint secondaryTrackPaint = Paint()..color = secondaryTrackColorTween.evaluate(enableAnimation)!; + if (isLTR) { + context.canvas.drawRRect( + RRect.fromLTRBAndCorners( + thumbCenter.dx + trackGap, + trackRect.top, + secondaryOffset.dx, + trackRect.bottom, + topLeft: trackInsideCornerRadius, + bottomLeft: trackInsideCornerRadius, + topRight: trackCornerRadius, + bottomRight: trackCornerRadius, + ), + secondaryTrackPaint, + ); + } else { + context.canvas.drawRRect( + RRect.fromLTRBAndCorners( + secondaryOffset.dx - trackGap, + trackRect.top, + thumbCenter.dx, + trackRect.bottom, + topLeft: trackInsideCornerRadius, + bottomLeft: trackInsideCornerRadius, + topRight: trackCornerRadius, + bottomRight: trackCornerRadius, + ), + secondaryTrackPaint, + ); + } + } + context.canvas.restore(); + + const double stopIndicatorRadius = 2.0; + final double stopIndicatorTrailingSpace = sliderTheme.trackHeight! / 2; + final Offset stopIndicatorOffset = Offset( + (textDirection == TextDirection.ltr) + ? trackRect.centerRight.dx - stopIndicatorTrailingSpace + : trackRect.centerLeft.dx + stopIndicatorTrailingSpace, + trackRect.center.dy, + ); + + final bool showStopIndicator = (textDirection == TextDirection.ltr) + ? thumbCenter.dx < stopIndicatorOffset.dx + : thumbCenter.dx > stopIndicatorOffset.dx; + if (showStopIndicator && !isDiscrete) { + final Rect stopIndicatorRect = Rect.fromCircle(center: stopIndicatorOffset, radius: stopIndicatorRadius); + context.canvas.drawCircle(stopIndicatorRect.center, stopIndicatorRadius, activePaint); + } + } + + @override + bool get isRounded => true; +} + +/// The rounded rectangle shape of a [Slider]'s value indicator. +/// +/// If the [SliderThemeData.valueIndicatorColor] is null, then the shape uses the [ColorScheme.inverseSurface] +/// color to draw the value indicator. +/// +/// If the [SliderThemeData.valueIndicatorTextStyle] is null, then the indicator label text style +/// defaults to [TextTheme.labelMedium] with the color set to [ColorScheme.onInverseSurface]. If the +/// [ThemeData.useMaterial3] is set to false, then the indicator label text style defaults to +/// [TextTheme.bodyLarge] with the color set to [ColorScheme.onInverseSurface]. +/// +/// If the [SliderThemeData.valueIndicatorStrokeColor] is provided, then the value indicator is drawn with a +/// stroke border with the color provided. +/// +/// This is the default value indicator shape for [Slider]. If [ThemeData.useMaterial3] is false, +/// then the default value indicator shape is [RectangularSliderValueIndicatorShape]. +/// +/// See also: +/// +/// * [Slider], which includes a value indicator defined by this shape. +/// * [SliderTheme], which can be used to configure the slider value indicator +/// of all sliders in a widget subtree. +class RoundedRectSliderValueIndicatorShape extends SliderComponentShape { + /// Create a slider value indicator that resembles a rounded rectangle. + const RoundedRectSliderValueIndicatorShape(); + + static const _RoundedRectSliderValueIndicatorPathPainter _pathPainter = _RoundedRectSliderValueIndicatorPathPainter(); + + @override + Size getPreferredSize( + bool isEnabled, + bool isDiscrete, { + TextPainter? labelPainter, + double? textScaleFactor, + }) { + assert(labelPainter != null); + assert(textScaleFactor != null && textScaleFactor >= 0); + return _pathPainter.getPreferredSize(labelPainter!, textScaleFactor!); + } + + @override + void paint( + PaintingContext context, + Offset center, { + required Animation activationAnimation, + required Animation enableAnimation, + required bool isDiscrete, + required TextPainter labelPainter, + required RenderBox parentBox, + required SliderThemeData sliderTheme, + required TextDirection textDirection, + required double value, + required double textScaleFactor, + required Size sizeWithOverflow, + }) { + final Canvas canvas = context.canvas; + final double scale = activationAnimation.value; + _pathPainter.paint( + parentBox: parentBox, + canvas: canvas, + center: center, + scale: scale, + labelPainter: labelPainter, + textScaleFactor: textScaleFactor, + sizeWithOverflow: sizeWithOverflow, + backgroundPaintColor: sliderTheme.valueIndicatorColor!, + strokePaintColor: sliderTheme.valueIndicatorStrokeColor, + ); + } +} + +class _RoundedRectSliderValueIndicatorPathPainter { + const _RoundedRectSliderValueIndicatorPathPainter(); + + static const double _labelPadding = 10.0; + static const double _preferredHeight = 32.0; + static const double _minLabelWidth = 16.0; + static const double _rectYOffset = 10.0; + static const double _bottomTipYOffset = 16.0; + static const double _preferredHalfHeight = _preferredHeight / 2; + + Size getPreferredSize( + TextPainter labelPainter, + double textScaleFactor, + ) { + final double width = math.max(_minLabelWidth, labelPainter.width) + (_labelPadding * 2) * textScaleFactor; + return Size(width, _preferredHeight * textScaleFactor); + } + + double getHorizontalShift({ + required RenderBox parentBox, + required Offset center, + required TextPainter labelPainter, + required double textScaleFactor, + required Size sizeWithOverflow, + required double scale, + }) { + assert(!sizeWithOverflow.isEmpty); + + const double edgePadding = 8.0; + final double rectangleWidth = _upperRectangleWidth(labelPainter, scale); + /// Value indicator draws on the Overlay and by using the global Offset + /// we are making sure we use the bounds of the Overlay instead of the Slider. + final Offset globalCenter = parentBox.localToGlobal(center); + + // The rectangle must be shifted towards the center so that it minimizes the + // chance of it rendering outside the bounds of the render box. If the shift + // is negative, then the lobe is shifted from right to left, and if it is + // positive, then the lobe is shifted from left to right. + final double overflowLeft = math.max(0, rectangleWidth / 2 - globalCenter.dx + edgePadding); + final double overflowRight = math.max(0, rectangleWidth / 2 - (sizeWithOverflow.width - globalCenter.dx - edgePadding)); + + if (rectangleWidth < sizeWithOverflow.width) { + return overflowLeft - overflowRight; + } else if (overflowLeft - overflowRight > 0) { + return overflowLeft - (edgePadding * textScaleFactor); + } else { + return -overflowRight + (edgePadding * textScaleFactor); + } + } + + double _upperRectangleWidth(TextPainter labelPainter, double scale) { + final double unscaledWidth = math.max(_minLabelWidth, labelPainter.width) + (_labelPadding * 2); + return unscaledWidth * scale; + } + + void paint({ + required RenderBox parentBox, + required Canvas canvas, + required Offset center, + required double scale, + required TextPainter labelPainter, + required double textScaleFactor, + required Size sizeWithOverflow, + required Color backgroundPaintColor, + Color? strokePaintColor, + }) { + if (scale == 0.0) { + // Zero scale essentially means "do not draw anything", so it's safe to just return. + return; + } + assert(!sizeWithOverflow.isEmpty); + + final double rectangleWidth = _upperRectangleWidth(labelPainter, scale); + final double horizontalShift = getHorizontalShift( + parentBox: parentBox, + center: center, + labelPainter: labelPainter, + textScaleFactor: textScaleFactor, + sizeWithOverflow: sizeWithOverflow, + scale: scale, + ); + + final Rect upperRect = Rect.fromLTWH( + -rectangleWidth / 2 + horizontalShift, + -_rectYOffset - _preferredHeight, + rectangleWidth, + _preferredHeight, + ); + + final Paint fillPaint = Paint()..color = backgroundPaintColor; + + canvas.save(); + // Prepare the canvas for the base of the tooltip, which is relative to the + // center of the thumb. + canvas.translate(center.dx, center.dy - _bottomTipYOffset); + canvas.scale(scale, scale); + + final RRect rrect = RRect.fromRectAndRadius(upperRect, Radius.circular(upperRect.height / 2)); + if (strokePaintColor != null) { + final Paint strokePaint = Paint() + ..color = strokePaintColor + ..strokeWidth = 1.0 + ..style = PaintingStyle.stroke; + canvas.drawRRect(rrect, strokePaint); + } + + canvas.drawRRect(rrect, fillPaint); + + // The label text is centered within the value indicator. + final double bottomTipToUpperRectTranslateY = -_preferredHalfHeight / 2 - upperRect.height; + canvas.translate(0, bottomTipToUpperRectTranslateY); + final Offset boxCenter = Offset(horizontalShift, upperRect.height / 2.3); + final Offset halfLabelPainterOffset = Offset(labelPainter.width / 2, labelPainter.height / 2); + final Offset labelOffset = boxCenter - halfLabelPainterOffset; + labelPainter.paint(canvas, labelOffset); + canvas.restore(); + } +} diff --git a/packages/flutter/lib/src/material/tab_bar_theme.dart b/packages/flutter/lib/src/material/tab_bar_theme.dart index 16c93c0275d..a38c6ffcaab 100644 --- a/packages/flutter/lib/src/material/tab_bar_theme.dart +++ b/packages/flutter/lib/src/material/tab_bar_theme.dart @@ -327,6 +327,7 @@ class TabBarThemeData with Diagnosticable { this.tabAlignment, this.textScaler, this.indicatorAnimation, + this.splashBorderRadius }); /// Overrides the default value for [TabBar.indicator]. @@ -389,6 +390,9 @@ class TabBarThemeData with Diagnosticable { /// Overrides the default value for [TabBar.indicatorAnimation]. final TabIndicatorAnimation? indicatorAnimation; + /// Defines the clipping radius of splashes that extend outside the bounds of the tab. + final BorderRadius? splashBorderRadius; + /// Creates a copy of this object but with the given fields replaced with the /// new values. TabBarThemeData copyWith({ @@ -408,6 +412,7 @@ class TabBarThemeData with Diagnosticable { TabAlignment? tabAlignment, TextScaler? textScaler, TabIndicatorAnimation? indicatorAnimation, + BorderRadius? splashBorderRadius, }) { return TabBarThemeData( indicator: indicator ?? this.indicator, @@ -426,6 +431,7 @@ class TabBarThemeData with Diagnosticable { tabAlignment: tabAlignment ?? this.tabAlignment, textScaler: textScaler ?? this.textScaler, indicatorAnimation: indicatorAnimation ?? this.indicatorAnimation, + splashBorderRadius: splashBorderRadius ?? this.splashBorderRadius, ); } @@ -453,6 +459,7 @@ class TabBarThemeData with Diagnosticable { tabAlignment: t < 0.5 ? a.tabAlignment : b.tabAlignment, textScaler: t < 0.5 ? a.textScaler : b.textScaler, indicatorAnimation: t < 0.5 ? a.indicatorAnimation : b.indicatorAnimation, + splashBorderRadius: BorderRadius.lerp(a.splashBorderRadius, a.splashBorderRadius, t) ); } @@ -474,6 +481,7 @@ class TabBarThemeData with Diagnosticable { tabAlignment, textScaler, indicatorAnimation, + splashBorderRadius, ); @override @@ -500,7 +508,8 @@ class TabBarThemeData with Diagnosticable { && other.mouseCursor == mouseCursor && other.tabAlignment == tabAlignment && other.textScaler == textScaler - && other.indicatorAnimation == indicatorAnimation; + && other.indicatorAnimation == indicatorAnimation + && other.splashBorderRadius == splashBorderRadius; } @override @@ -522,5 +531,6 @@ class TabBarThemeData with Diagnosticable { properties.add(DiagnosticsProperty('tabAlignment', tabAlignment, defaultValue: null)); properties.add(DiagnosticsProperty('textScaler', textScaler, defaultValue: null)); properties.add(DiagnosticsProperty('indicatorAnimation', indicatorAnimation, defaultValue: null)); + properties.add(DiagnosticsProperty('splashBorderRadius', splashBorderRadius, defaultValue: null)); } } diff --git a/packages/flutter/lib/src/material/tabs.dart b/packages/flutter/lib/src/material/tabs.dart index dc8c9f03f9e..defc21b174a 100644 --- a/packages/flutter/lib/src/material/tabs.dart +++ b/packages/flutter/lib/src/material/tabs.dart @@ -1772,11 +1772,9 @@ class _TabBarState extends State { wrappedTabs[previousIndex] = _buildStyledTab(wrappedTabs[previousIndex], false, animation, _defaults); } else { // The user is dragging the TabBarView's PageView left or right. - if (_currentIndex! < widget.tabs.length) { - final int tabIndex = _currentIndex!; - final Animation centerAnimation = _DragAnimation(_controller!, tabIndex); - wrappedTabs[tabIndex] = _buildStyledTab(wrappedTabs[tabIndex], true, centerAnimation, _defaults); - } + final int tabIndex = _currentIndex!; + final Animation centerAnimation = _DragAnimation(_controller!, tabIndex); + wrappedTabs[tabIndex] = _buildStyledTab(wrappedTabs[tabIndex], true, centerAnimation, _defaults); if (_currentIndex! > 0) { final int tabIndex = _currentIndex! - 1; final Animation previousAnimation = ReverseAnimation(_DragAnimation(_controller!, tabIndex)); @@ -1815,7 +1813,7 @@ class _TabBarState extends State { enableFeedback: widget.enableFeedback ?? true, overlayColor: widget.overlayColor ?? tabBarTheme.overlayColor ?? defaultOverlay, splashFactory: widget.splashFactory ?? tabBarTheme.splashFactory ?? _defaults.splashFactory, - borderRadius: widget.splashBorderRadius, + borderRadius: widget.splashBorderRadius ?? tabBarTheme.splashBorderRadius ?? _defaults.splashBorderRadius, child: Padding( padding: EdgeInsets.only(bottom: widget.indicatorWeight), child: Stack( diff --git a/packages/flutter/lib/src/material/text_button.dart b/packages/flutter/lib/src/material/text_button.dart index 39cb598443e..2ff5ece1182 100644 --- a/packages/flutter/lib/src/material/text_button.dart +++ b/packages/flutter/lib/src/material/text_button.dart @@ -93,7 +93,6 @@ class TextButton extends ButtonStyleButton { super.statesController, super.isSemanticButton, required Widget super.child, - super.iconAlignment, }); /// Create a text button from a pair of widgets that serve as the button's @@ -119,7 +118,7 @@ class TextButton extends ButtonStyleButton { MaterialStatesController? statesController, Widget? icon, required Widget label, - IconAlignment iconAlignment = IconAlignment.start, + IconAlignment? iconAlignment, }) { if (icon == null) { return TextButton( @@ -204,6 +203,7 @@ class TextButton extends ButtonStyleButton { Color? surfaceTintColor, Color? iconColor, double? iconSize, + IconAlignment? iconAlignment, Color? disabledIconColor, Color? overlayColor, double? elevation, @@ -254,6 +254,7 @@ class TextButton extends ButtonStyleButton { surfaceTintColor: ButtonStyleButton.allOrNull(surfaceTintColor), iconColor: iconColorProp, iconSize: ButtonStyleButton.allOrNull(iconSize), + iconAlignment: iconAlignment, elevation: ButtonStyleButton.allOrNull(elevation), padding: ButtonStyleButton.allOrNull(padding), minimumSize: ButtonStyleButton.allOrNull(minimumSize), @@ -456,7 +457,7 @@ class _TextButtonWithIcon extends TextButton { super.statesController, required Widget icon, required Widget label, - super.iconAlignment, + IconAlignment? iconAlignment, }) : super( autofocus: autofocus ?? false, child: _TextButtonWithIconChild( @@ -496,16 +497,21 @@ class _TextButtonWithIconChild extends StatelessWidget { final Widget label; final Widget icon; final ButtonStyle? buttonStyle; - final IconAlignment iconAlignment; + final IconAlignment? iconAlignment; @override Widget build(BuildContext context) { final double defaultFontSize = buttonStyle?.textStyle?.resolve(const {})?.fontSize ?? 14.0; final double scale = clampDouble(MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0, 1.0, 2.0) - 1.0; final double gap = lerpDouble(8, 4, scale)!; + final TextButtonThemeData textButtonTheme = TextButtonTheme.of(context); + final IconAlignment effectiveIconAlignment = iconAlignment + ?? textButtonTheme.style?.iconAlignment + ?? buttonStyle?.iconAlignment + ?? IconAlignment.start; return Row( mainAxisSize: MainAxisSize.min, - children: iconAlignment == IconAlignment.start + children: effectiveIconAlignment == IconAlignment.start ? [icon, SizedBox(width: gap), Flexible(child: label)] : [Flexible(child: label), SizedBox(width: gap), icon], ); diff --git a/packages/flutter/lib/src/material/text_field.dart b/packages/flutter/lib/src/material/text_field.dart index 034a197eda4..18095fdd979 100644 --- a/packages/flutter/lib/src/material/text_field.dart +++ b/packages/flutter/lib/src/material/text_field.dart @@ -301,7 +301,12 @@ class TextField extends StatefulWidget { this.contentInsertionConfiguration, this.clipBehavior = Clip.hardEdge, this.restorationId, + @Deprecated( + 'Use `stylusHandwritingEnabled` instead. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) this.scribbleEnabled = true, + this.stylusHandwritingEnabled = EditableText.defaultStylusHandwritingEnabled, this.enableIMEPersonalizedLearning = true, this.contextMenuBuilder = _defaultContextMenuBuilder, this.canRequestFocus = true, @@ -797,8 +802,15 @@ class TextField extends StatefulWidget { final String? restorationId; /// {@macro flutter.widgets.editableText.scribbleEnabled} + @Deprecated( + 'Use `stylusHandwritingEnabled` instead. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) final bool scribbleEnabled; + /// {@macro flutter.widgets.editableText.stylusHandwritingEnabled} + final bool stylusHandwritingEnabled; + /// {@macro flutter.services.TextInputConfiguration.enableIMEPersonalizedLearning} final bool enableIMEPersonalizedLearning; @@ -948,6 +960,7 @@ class TextField extends StatefulWidget { properties.add(DiagnosticsProperty('scrollPhysics', scrollPhysics, defaultValue: null)); properties.add(DiagnosticsProperty('clipBehavior', clipBehavior, defaultValue: Clip.hardEdge)); properties.add(DiagnosticsProperty('scribbleEnabled', scribbleEnabled, defaultValue: true)); + properties.add(DiagnosticsProperty('stylusHandwritingEnabled', stylusHandwritingEnabled, defaultValue: EditableText.defaultStylusHandwritingEnabled)); properties.add(DiagnosticsProperty('enableIMEPersonalizedLearning', enableIMEPersonalizedLearning, defaultValue: true)); properties.add(DiagnosticsProperty('spellCheckConfiguration', spellCheckConfiguration, defaultValue: null)); properties.add(DiagnosticsProperty>('contentCommitMimeTypes', contentInsertionConfiguration?.allowedMimeTypes ?? const [], defaultValue: contentInsertionConfiguration == null ? const [] : kDefaultContentInsertionMimeTypes)); @@ -1514,6 +1527,7 @@ class _TextFieldState extends State with RestorationMixin implements clipBehavior: widget.clipBehavior, restorationId: 'editable', scribbleEnabled: widget.scribbleEnabled, + stylusHandwritingEnabled: widget.stylusHandwritingEnabled, enableIMEPersonalizedLearning: widget.enableIMEPersonalizedLearning, contentInsertionConfiguration: widget.contentInsertionConfiguration, contextMenuBuilder: widget.contextMenuBuilder, diff --git a/packages/flutter/lib/src/material/text_form_field.dart b/packages/flutter/lib/src/material/text_form_field.dart index 2e2760a7d8f..eccabddd3cc 100644 --- a/packages/flutter/lib/src/material/text_form_field.dart +++ b/packages/flutter/lib/src/material/text_form_field.dart @@ -182,7 +182,12 @@ class TextFormField extends FormField { ContentInsertionConfiguration? contentInsertionConfiguration, MaterialStatesController? statesController, Clip clipBehavior = Clip.hardEdge, + @Deprecated( + 'Use `stylusHandwritingEnabled` instead. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) bool scribbleEnabled = true, + bool stylusHandwritingEnabled = EditableText.defaultStylusHandwritingEnabled, bool canRequestFocus = true, }) : assert(initialValue == null || controller == null), assert(obscuringCharacter.length == 1), @@ -279,6 +284,7 @@ class TextFormField extends FormField { contentInsertionConfiguration: contentInsertionConfiguration, clipBehavior: clipBehavior, scribbleEnabled: scribbleEnabled, + stylusHandwritingEnabled: stylusHandwritingEnabled, canRequestFocus: canRequestFocus, ), ); diff --git a/packages/flutter/lib/src/material/tooltip.dart b/packages/flutter/lib/src/material/tooltip.dart index d994d37af34..778aff0e267 100644 --- a/packages/flutter/lib/src/material/tooltip.dart +++ b/packages/flutter/lib/src/material/tooltip.dart @@ -46,6 +46,7 @@ class _ExclusiveMouseRegion extends MouseRegion { const _ExclusiveMouseRegion({ super.onEnter, super.onExit, + super.cursor, super.child, }); @@ -54,6 +55,7 @@ class _ExclusiveMouseRegion extends MouseRegion { return _RenderExclusiveMouseRegion( onEnter: onEnter, onExit: onExit, + cursor: cursor, ); } } @@ -62,6 +64,7 @@ class _RenderExclusiveMouseRegion extends RenderMouseRegion { _RenderExclusiveMouseRegion({ super.onEnter, super.onExit, + super.cursor, }); static bool isOutermostMouseRegion = true; @@ -195,6 +198,7 @@ class Tooltip extends StatefulWidget { this.triggerMode, this.enableFeedback, this.onTriggered, + this.mouseCursor, this.child, }) : assert((message == null) != (richMessage == null), 'Either `message` or `richMessage` must be specified'), assert( @@ -363,6 +367,12 @@ class Tooltip extends StatefulWidget { /// or after a long press when [triggerMode] is [TooltipTriggerMode.longPress]. final TooltipTriggeredCallback? onTriggered; + /// The cursor for a mouse pointer when it enters or is hovering over the + /// widget. + /// + /// If this property is null, [MouseCursor.defer] will be used. + final MouseCursor? mouseCursor; + static final List _openedTooltips = []; /// Dismiss all of the tooltips that are currently shown on the screen, @@ -706,6 +716,7 @@ class TooltipState extends State with SingleTickerProviderStateMixin { return true; } + @protected @override void initState() { super.initState(); @@ -715,6 +726,7 @@ class TooltipState extends State with SingleTickerProviderStateMixin { GestureBinding.instance.pointerRouter.addGlobalRoute(_handleGlobalPointerEvent); } + @protected @override void didChangeDependencies() { super.didChangeDependencies(); @@ -797,6 +809,7 @@ class TooltipState extends State with SingleTickerProviderStateMixin { : SelectionContainer.disabled(child: overlayChild); } + @protected @override void dispose() { GestureBinding.instance.pointerRouter.removeGlobalRoute(_handleGlobalPointerEvent); @@ -815,6 +828,7 @@ class TooltipState extends State with SingleTickerProviderStateMixin { super.dispose(); } + @protected @override Widget build(BuildContext context) { // If message is empty then no need to create a tooltip overlay to show @@ -835,6 +849,7 @@ class TooltipState extends State with SingleTickerProviderStateMixin { result = _ExclusiveMouseRegion( onEnter: _handleMouseEnter, onExit: _handleMouseExit, + cursor: widget.mouseCursor ?? MouseCursor.defer, child: Listener( onPointerDown: _handlePointerDown, behavior: HitTestBehavior.opaque, diff --git a/packages/flutter/lib/src/painting/_network_image_web.dart b/packages/flutter/lib/src/painting/_network_image_web.dart index 257e48e0478..eecfc9a6b31 100644 --- a/packages/flutter/lib/src/painting/_network_image_web.dart +++ b/packages/flutter/lib/src/painting/_network_image_web.dart @@ -10,28 +10,52 @@ import 'dart:ui_web' as ui_web; import 'package:flutter/foundation.dart'; import '../web.dart' as web; +import '_web_image_info_web.dart'; import 'image_provider.dart' as image_provider; import 'image_stream.dart'; -/// Creates a type for an overridable factory function for testing purposes. +/// The type for an overridable factory function for creating an HTTP request, +/// used for testing purposes. typedef HttpRequestFactory = web.XMLHttpRequest Function(); +/// The type for an overridable factory function for creating elements, +/// used for testing purposes. +typedef ImgElementFactory = web.HTMLImageElement Function(); + // Method signature for _loadAsync decode callbacks. typedef _SimpleDecoderCallback = Future Function(ui.ImmutableBuffer buffer); -/// Default HTTP client. +/// The default HTTP client. web.XMLHttpRequest _httpClient() { return web.XMLHttpRequest(); } /// Creates an overridable factory function. +@visibleForTesting HttpRequestFactory httpRequestFactory = _httpClient; -/// Restores to the default HTTP request factory. +/// Restores the default HTTP request factory. +@visibleForTesting void debugRestoreHttpRequestFactory() { httpRequestFactory = _httpClient; } +/// The default element factory. +web.HTMLImageElement _imgElementFactory() { + return web.document.createElement('img') as web.HTMLImageElement; +} + +/// The factory function that creates elements, can be overridden for +/// tests. +@visibleForTesting +ImgElementFactory imgElementFactory = _imgElementFactory; + +/// Restores the default element factory. +@visibleForTesting +void debugRestoreImgElementFactory() { + imgElementFactory = _imgElementFactory; +} + /// The web implementation of [image_provider.NetworkImage]. /// /// NetworkImage on the web does not support decoding to a specified size. @@ -64,12 +88,14 @@ class NetworkImage final StreamController chunkEvents = StreamController(); - return MultiFrameImageStreamCompleter( - chunkEvents: chunkEvents.stream, - codec: _loadAsync(key as NetworkImage, decode, chunkEvents), - scale: key.scale, - debugLabel: key.url, + return _ForwardingImageStreamCompleter( + _loadAsync( + key as NetworkImage, + decode, + chunkEvents, + ), informationCollector: _imageStreamInformationCollector(key), + debugLabel: key.url, ); } @@ -80,12 +106,14 @@ class NetworkImage // has been loaded or an error is thrown. final StreamController chunkEvents = StreamController(); - return MultiFrameImageStreamCompleter( - chunkEvents: chunkEvents.stream, - codec: _loadAsync(key as NetworkImage, decode, chunkEvents), - scale: key.scale, - debugLabel: key.url, + return _ForwardingImageStreamCompleter( + _loadAsync( + key as NetworkImage, + decode, + chunkEvents, + ), informationCollector: _imageStreamInformationCollector(key), + debugLabel: key.url, ); } @@ -101,10 +129,10 @@ class NetworkImage return collector; } - // Html renderer does not support decoding network images to a specified size. The decode parameter + // HTML renderer does not support decoding network images to a specified size. The decode parameter // here is ignored and `ui_web.createImageCodecFromUrl` will be used directly // in place of the typical `instantiateImageCodec` method. - Future _loadAsync( + Future _loadAsync( NetworkImage key, _SimpleDecoderCallback decode, StreamController chunkEvents, @@ -117,62 +145,143 @@ class NetworkImage // We use a different method when headers are set because the // `ui_web.createImageCodecFromUrl` method is not capable of handling headers. - if (isSkiaWeb || containsNetworkImageHeaders) { - final Completer completer = - Completer(); - final web.XMLHttpRequest request = httpRequestFactory(); + if (containsNetworkImageHeaders) { + // It is not possible to load an element and pass the headers with + // the request to fetch the image. Since the user has provided headers, + // this function should assume the headers are required to resolve to + // the correct resource and should not attempt to load the image in an + // tag without the headers. - request.open('GET', key.url, true); - request.responseType = 'arraybuffer'; - if (containsNetworkImageHeaders) { - key.headers!.forEach((String header, String value) { - request.setRequestHeader(header, value); - }); + // Resolve the Codec before passing it to + // [MultiFrameImageStreamCompleter] so any errors aren't reported + // twice (once from the MultiFrameImageStreamCompleter and again + // from the wrapping [ForwardingImageStreamCompleter]). + final ui.Codec codec = await _fetchImageBytes(decode); + return MultiFrameImageStreamCompleter( + chunkEvents: chunkEvents.stream, + codec: Future.value(codec), + scale: key.scale, + debugLabel: key.url, + informationCollector: _imageStreamInformationCollector(key), + ); + } else if (isSkiaWeb) { + try { + // Resolve the Codec before passing it to + // [MultiFrameImageStreamCompleter] so any errors aren't reported + // twice (once from the MultiFrameImageStreamCompleter and again + // from the wrapping [ForwardingImageStreamCompleter]). + final ui.Codec codec = await _fetchImageBytes(decode); + return MultiFrameImageStreamCompleter( + chunkEvents: chunkEvents.stream, + codec: Future.value(codec), + scale: key.scale, + debugLabel: key.url, + informationCollector: _imageStreamInformationCollector(key), + ); + } catch (e) { + // If we failed to fetch the bytes, try to load the image in an + // element instead. + final web.HTMLImageElement imageElement = imgElementFactory(); + imageElement.src = key.url; + // Decode the element before creating the ImageStreamCompleter + // to avoid double reporting the error. + await imageElement.decode().toDart; + return OneFrameImageStreamCompleter( + Future.value( + WebImageInfo( + imageElement, + debugLabel: key.url, + ), + ), + informationCollector: _imageStreamInformationCollector(key), + )..debugLabel = key.url; } - - request.addEventListener('load', (web.Event e) { - final int status = request.status; - final bool accepted = status >= 200 && status < 300; - final bool fileUri = status == 0; // file:// URIs have status of 0. - final bool notModified = status == 304; - final bool unknownRedirect = status > 307 && status < 400; - final bool success = - accepted || fileUri || notModified || unknownRedirect; - - if (success) { - completer.complete(request); - } else { - completer.completeError(e); - throw image_provider.NetworkImageLoadException( - statusCode: status, uri: resolved); - } - }.toJS); - - request.addEventListener('error', - ((JSObject e) => completer.completeError(e)).toJS); - - request.send(); - - await completer.future; - - final Uint8List bytes = (request.response! as JSArrayBuffer).toDart.asUint8List(); - - if (bytes.lengthInBytes == 0) { - throw image_provider.NetworkImageLoadException( - statusCode: request.status, uri: resolved); - } - return decode(await ui.ImmutableBuffer.fromUint8List(bytes)); } else { - return ui_web.createImageCodecFromUrl( - resolved, - chunkCallback: (int bytes, int total) { - chunkEvents.add(ImageChunkEvent( - cumulativeBytesLoaded: bytes, expectedTotalBytes: total)); - }, + // This branch is only hit by the HTML renderer, which is deprecated. The + // HTML renderer supports loading images with CORS restrictions, so we + // don't need to catch errors and try loading the image in an tag + // in this case. + + // Resolve the Codec before passing it to + // [MultiFrameImageStreamCompleter] so any errors aren't reported + // twice (once from the MultiFrameImageStreamCompleter) and again + // from the wrapping [ForwardingImageStreamCompleter]. + final ui.Codec codec = await ui_web.createImageCodecFromUrl( + resolved, + chunkCallback: (int bytes, int total) { + chunkEvents.add(ImageChunkEvent( + cumulativeBytesLoaded: bytes, expectedTotalBytes: total)); + }, + ); + return MultiFrameImageStreamCompleter( + chunkEvents: chunkEvents.stream, + codec: Future.value(codec), + scale: key.scale, + debugLabel: key.url, + informationCollector: _imageStreamInformationCollector(key), ); } } + Future _fetchImageBytes( + _SimpleDecoderCallback decode, + ) async { + final Uri resolved = Uri.base.resolve(url); + + final bool containsNetworkImageHeaders = headers?.isNotEmpty ?? false; + + final Completer completer = + Completer(); + final web.XMLHttpRequest request = httpRequestFactory(); + + request.open('GET', url, true); + request.responseType = 'arraybuffer'; + if (containsNetworkImageHeaders) { + headers!.forEach((String header, String value) { + request.setRequestHeader(header, value); + }); + } + + request.addEventListener('load', (web.Event e) { + final int status = request.status; + final bool accepted = status >= 200 && status < 300; + final bool fileUri = status == 0; // file:// URIs have status of 0. + final bool notModified = status == 304; + final bool unknownRedirect = status > 307 && status < 400; + final bool success = + accepted || fileUri || notModified || unknownRedirect; + + if (success) { + completer.complete(request); + } else { + completer.completeError(image_provider.NetworkImageLoadException( + statusCode: status, uri: resolved)); + } + }.toJS); + + request.addEventListener( + 'error', + ((JSObject e) => + completer.completeError(image_provider.NetworkImageLoadException( + statusCode: request.status, + uri: resolved, + ))).toJS, + ); + + request.send(); + + await completer.future; + + final Uint8List bytes = (request.response! as JSArrayBuffer).toDart.asUint8List(); + + if (bytes.lengthInBytes == 0) { + throw image_provider.NetworkImageLoadException( + statusCode: request.status, uri: resolved); + } + + return decode(await ui.ImmutableBuffer.fromUint8List(bytes)); + } + @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { @@ -187,3 +296,61 @@ class NetworkImage @override String toString() => '${objectRuntimeType(this, 'NetworkImage')}("$url", scale: ${scale.toStringAsFixed(1)})'; } + +/// An [ImageStreamCompleter] that delegates to another [ImageStreamCompleter] +/// that is loaded asynchronously. +/// +/// This completer keeps its child completer alive until this completer is disposed. +class _ForwardingImageStreamCompleter extends ImageStreamCompleter { + _ForwardingImageStreamCompleter(this.task, + {InformationCollector? informationCollector, String? debugLabel}) { + this.debugLabel = debugLabel; + task.then((ImageStreamCompleter value) { + resolved = true; + if (_disposed) { + // Add a listener since the delegate completer won't dispose if it never + // had a listener. + value.addListener(ImageStreamListener((_, __) {})); + value.maybeDispose(); + return; + } + completer = value; + handle = completer.keepAlive(); + completer.addListener(ImageStreamListener( + (ImageInfo image, bool synchronousCall) { + setImage(image); + }, + onChunk: (ImageChunkEvent event) { + reportImageChunkEvent(event); + }, + onError:(Object exception, StackTrace? stackTrace) { + reportError(exception: exception, stack: stackTrace); + }, + )); + }, onError: (Object error, StackTrace stack) { + reportError( + context: ErrorDescription('resolving an image stream completer'), + exception: error, + stack: stack, + informationCollector: informationCollector, + silent: true, + ); + }); + } + + final Future task; + bool resolved = false; + late final ImageStreamCompleter completer; + late final ImageStreamCompleterHandle handle; + + bool _disposed = false; + + @override + void onDisposed() { + if (resolved) { + handle.dispose(); + } + _disposed = true; + super.onDisposed(); + } +} diff --git a/packages/flutter/lib/src/painting/_web_image_info_io.dart b/packages/flutter/lib/src/painting/_web_image_info_io.dart new file mode 100644 index 00000000000..a88b52b70eb --- /dev/null +++ b/packages/flutter/lib/src/painting/_web_image_info_io.dart @@ -0,0 +1,40 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:ui' as ui; + +import 'image_stream.dart'; + +/// An [ImageInfo] object indicating that the image can only be displayed in +/// an element, and no [dart:ui.Image] can be created for it. +/// +/// This occurs on the web when the image resource is from a different origin +/// and is not configured for CORS. Since the image bytes cannot be directly +/// fetched, [ui.Image]s cannot be created from it. However, the image can +/// still be displayed if an element is used. +class WebImageInfo implements ImageInfo { + @override + ImageInfo clone() => _unsupported(); + + @override + String? get debugLabel => _unsupported(); + + @override + void dispose() => _unsupported(); + + @override + ui.Image get image => _unsupported(); + + @override + bool isCloneOf(ImageInfo other) => _unsupported(); + + @override + double get scale => _unsupported(); + + @override + int get sizeBytes => _unsupported(); + + Never _unsupported() => throw UnsupportedError( + 'WebImageInfo should never be instantiated in a non-web context.'); +} diff --git a/packages/flutter/lib/src/painting/_web_image_info_web.dart b/packages/flutter/lib/src/painting/_web_image_info_web.dart new file mode 100644 index 00000000000..ee8468351cb --- /dev/null +++ b/packages/flutter/lib/src/painting/_web_image_info_web.dart @@ -0,0 +1,70 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:ui'; + +import '../web.dart' as web; +import 'image_stream.dart'; + +/// An [ImageInfo] object indicating that the image can only be displayed in +/// an element, and no [dart:ui.Image] can be created for it. +/// +/// This occurs on the web when the image resource is from a different origin +/// and is not configured for CORS. Since the image bytes cannot be directly +/// fetched, [ui.Image]s cannot be created from it. However, the image can +/// still be displayed if an element is used. +class WebImageInfo implements ImageInfo { + /// Creates a new [WebImageInfo] from a given element. + WebImageInfo(this.htmlImage, {this.debugLabel}); + + /// The element used to display this image. This element has + /// already been decoded, so size information can be retrieved from it. + final web.HTMLImageElement htmlImage; + + @override + final String? debugLabel; + + @override + WebImageInfo clone() { + // There is no need to actually clone the element here. We create + // another reference to the element and let the browser garbage + // collect it when there are no more live references. + return WebImageInfo( + htmlImage, + debugLabel: debugLabel, + ); + } + + @override + void dispose() { + // There is nothing to do here. There is no way to delete an element + // directly, the most we can do is remove it from the DOM. But the + // element here is never even added to the DOM. The browser will + // automatically garbage collect the element when there are no longer any + // live references to it. + } + + @override + Image get image => throw UnsupportedError( + 'Could not create image data for this image because access to it is ' + 'restricted by the Same-Origin Policy.\n' + 'See https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy'); + + @override + bool isCloneOf(ImageInfo other) { + if (other is! WebImageInfo) { + return false; + } + + // It is a clone if it points to the same element. + return other.htmlImage == htmlImage && other.debugLabel == debugLabel; + } + + @override + double get scale => 1.0; + + @override + int get sizeBytes => + (4 * htmlImage.naturalWidth * htmlImage.naturalHeight).toInt(); +} diff --git a/packages/flutter/lib/src/painting/colors.dart b/packages/flutter/lib/src/painting/colors.dart index b7486265768..a897c0b33d6 100644 --- a/packages/flutter/lib/src/painting/colors.dart +++ b/packages/flutter/lib/src/painting/colors.dart @@ -495,17 +495,8 @@ class ColorProperty extends DiagnosticsProperty { }); @override - Map toJsonMap( - DiagnosticsSerializationDelegate delegate, { - bool fullDetails = true, - }) { - final Map json = super.toJsonMap( - delegate, - fullDetails: fullDetails, - ); - if (!fullDetails) { - return json; - } + Map toJsonMap(DiagnosticsSerializationDelegate delegate) { + final Map json = super.toJsonMap(delegate); if (value != null) { json['valueProperties'] = { 'red': value!.red, diff --git a/packages/flutter/lib/src/painting/image_stream.dart b/packages/flutter/lib/src/painting/image_stream.dart index f43942a8c30..8cb03f2af76 100644 --- a/packages/flutter/lib/src/painting/image_stream.dart +++ b/packages/flutter/lib/src/painting/image_stream.dart @@ -690,6 +690,24 @@ abstract class ImageStreamCompleter with Diagnosticable { bool _disposed = false; + /// Called when this [ImageStreamCompleter] has actually been disposed. + /// + /// Subclasses should override this if they need to clean up resources when + /// they are disposed. + @mustCallSuper + @protected + void onDisposed() {} + + /// Disposes this [ImageStreamCompleter] unless: + /// 1. It has never had a listener + /// 2. It is already disposed + /// 3. It has listeners. + /// 4. It has active "keep alive" handles. + @nonVirtual + void maybeDispose() { + _maybeDispose(); + } + @mustCallSuper void _maybeDispose() { if (!_hadAtLeastOneListener || _disposed || _listeners.isNotEmpty || _keepAliveHandles != 0) { @@ -700,6 +718,7 @@ abstract class ImageStreamCompleter with Diagnosticable { _currentImage?.dispose(); _currentImage = null; _disposed = true; + onDisposed(); } void _checkDisposed() { diff --git a/packages/flutter/lib/src/physics/spring_simulation.dart b/packages/flutter/lib/src/physics/spring_simulation.dart index 2faa724b877..1a918ba4e38 100644 --- a/packages/flutter/lib/src/physics/spring_simulation.dart +++ b/packages/flutter/lib/src/physics/spring_simulation.dart @@ -139,17 +139,25 @@ class SpringSimulation extends Simulation { /// The units for the velocity are L/T, where L is the aforementioned /// arbitrary unit of length, and T is the time unit used for driving the /// [SpringSimulation]. + /// + /// If `snapToEnd` is true, [x] will be set to `end` and [dx] to 0 when + /// [isDone] returns true. This is useful for transitions that require the + /// simulation to stop exactly at the end value, since the spring may not + /// naturally reach the target precisely. Defaults to false. SpringSimulation( SpringDescription spring, double start, double end, double velocity, { + bool snapToEnd = false, super.tolerance, }) : _endPosition = end, - _solution = _SpringSolution(spring, start - end, velocity); + _solution = _SpringSolution(spring, start - end, velocity), + _snapToEnd = snapToEnd; final double _endPosition; final _SpringSolution _solution; + final bool _snapToEnd; /// The kind of spring being simulated, for debugging purposes. /// @@ -158,10 +166,22 @@ class SpringSimulation extends Simulation { SpringType get type => _solution.type; @override - double x(double time) => _endPosition + _solution.x(time); + double x(double time) { + if (_snapToEnd && isDone(time)) { + return _endPosition; + } else { + return _endPosition + _solution.x(time); + } + } @override - double dx(double time) => _solution.dx(time); + double dx(double time) { + if (_snapToEnd && isDone(time)) { + return 0; + } else { + return _solution.dx(time); + } + } @override bool isDone(double time) { diff --git a/packages/flutter/lib/src/rendering/editable.dart b/packages/flutter/lib/src/rendering/editable.dart index 4b2a973bb70..d6f5eddc3c6 100644 --- a/packages/flutter/lib/src/rendering/editable.dart +++ b/packages/flutter/lib/src/rendering/editable.dart @@ -2550,6 +2550,12 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, super.paint, Offset.zero, ); + } else if (selection!.isCollapsed) { + context.pushLayer( + LeaderLayer(link: endHandleLayerLink, offset: startPoint + offset), + super.paint, + Offset.zero, + ); } } diff --git a/packages/flutter/lib/src/rendering/object.dart b/packages/flutter/lib/src/rendering/object.dart index 1c3b3c051ed..140ee48a6ed 100644 --- a/packages/flutter/lib/src/rendering/object.dart +++ b/packages/flutter/lib/src/rendering/object.dart @@ -2958,7 +2958,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge if (!isRepaintBoundary && _wasRepaintBoundary) { _needsPaint = false; _needsCompositedLayerUpdate = false; - owner?._nodesNeedingPaint.remove(this); + owner?._nodesNeedingPaint.removeWhere((RenderObject t) => identical(t, this)); _needsCompositingBitsUpdate = false; markNeedsPaint(); } else if (oldNeedsCompositing != _needsCompositing) { @@ -4353,6 +4353,12 @@ mixin ContainerRenderObjectMixin (TextSelectionHandleType.collapsed, TextSelectionHandleType.collapsed), + (false, true) => (TextSelectionHandleType.right, TextSelectionHandleType.left), + (false, false) => (TextSelectionHandleType.left, TextSelectionHandleType.right), + }; return SelectionGeometry( startSelectionPoint: SelectionPoint( localPosition: startOffsetInParagraphCoordinates, lineHeight: paragraph._textPainter.preferredLineHeight, - handleType: flipHandles ? TextSelectionHandleType.right : TextSelectionHandleType.left + handleType: startSelectionHandleType, ), endSelectionPoint: SelectionPoint( localPosition: endOffsetInParagraphCoordinates, lineHeight: paragraph._textPainter.preferredLineHeight, - handleType: flipHandles ? TextSelectionHandleType.left : TextSelectionHandleType.right, + handleType: endSelectionHandleType, ), selectionRects: selectionRects, - status: _textSelectionStart!.offset == _textSelectionEnd!.offset + status: selectionCollapsed ? SelectionStatus.collapsed : SelectionStatus.uncollapsed, hasContent: true, @@ -1483,6 +1496,17 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem ); } + @override + SelectedContentRange? getSelection() { + if (_textSelectionStart == null || _textSelectionEnd == null) { + return null; + } + return SelectedContentRange( + startOffset: _textSelectionStart!.offset, + endOffset: _textSelectionEnd!.offset, + ); + } + void _didChangeSelection() { paragraph.markNeedsPaint(); _updateSelectionGeometry(); @@ -3044,6 +3068,9 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem _cachedBoundingBoxes = null; } + @override + int get contentLength => range.end - range.start; + @override Size get size { return _rect.size; diff --git a/packages/flutter/lib/src/rendering/selection.dart b/packages/flutter/lib/src/rendering/selection.dart index f8d3b60a1f4..f486529f5b0 100644 --- a/packages/flutter/lib/src/rendering/selection.dart +++ b/packages/flutter/lib/src/rendering/selection.dart @@ -90,6 +90,11 @@ abstract class SelectionHandler implements ValueListenable { /// Return `null` if nothing is selected. SelectedContent? getSelectedContent(); + /// Gets the [SelectedContentRange] representing the selected range in this object. + /// + /// When nothing is selected, subclasses should return `null`. + SelectedContentRange? getSelection(); + /// Handles the [SelectionEvent] sent to this object. /// /// The subclasses need to update their selections or delegate the @@ -102,19 +107,113 @@ abstract class SelectionHandler implements ValueListenable { /// See also: /// * [SelectionEventType], which contains all of the possible types. SelectionResult dispatchSelectionEvent(SelectionEvent event); + + /// The length of the content in this object. + int get contentLength; +} + +/// This class stores the range information of the selection under a [Selectable] +/// or [SelectionHandler]. +/// +/// The [SelectedContentRange] for a given [Selectable] or [SelectionHandler] +/// can be retrieved by calling [SelectionHandler.getSelection]. +@immutable +class SelectedContentRange with Diagnosticable { + /// Creates a [SelectedContentRange] with the given values. + const SelectedContentRange({ + required this.startOffset, + required this.endOffset, + }) : assert((startOffset >= 0 && endOffset >= 0)); + + /// The start of the selection relative to the start of the content. + /// + /// {@template flutter.rendering.selection.SelectedContentRange.selectionOffsets} + /// For example a [Text] widget's content is in the format of an [TextSpan] tree. + /// + /// Take the [Text] widget and [TextSpan] tree below: + /// + /// {@tool snippet} + /// ```dart + /// const Text.rich( + /// TextSpan( + /// text: 'Hello world, ', + /// children: [ + /// WidgetSpan( + /// child: Text('how are you today? '), + /// ), + /// TextSpan( + /// text: 'Good, thanks for asking.', + /// ), + /// ], + /// ), + /// ) + /// ``` + /// {@end-tool} + /// + /// If we select from the beginning of 'world' to the end of the '.' + /// at the end of the [TextSpan] tree, the [SelectedContentRange] from + /// [SelectionHandler.getSelection] will be relative to the text of the + /// [TextSpan] tree, with [WidgetSpan] content being flattened. The [startOffset] + /// will be 6, and [endOffset] will be 56. This takes into account the + /// length of the content in the [WidgetSpan], which is 19, making the overall + /// length of the content 56. + /// {@endtemplate} + final int startOffset; + + /// The end of the selection relative to the start of the content. + /// + /// {@macro flutter.rendering.selection.SelectedContentRange.selectionOffsets} + final int endOffset; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + if (other.runtimeType != runtimeType) { + return false; + } + return other is SelectedContentRange + && other.startOffset == startOffset + && other.endOffset == endOffset; + } + + @override + int get hashCode { + return Object.hash( + startOffset, + endOffset, + ); + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(IntProperty('startOffset', startOffset)); + properties.add(IntProperty('endOffset', endOffset)); + } } /// The selected content in a [Selectable] or [SelectionHandler]. // TODO(chunhtai): Add more support for rich content. // https://github.com/flutter/flutter/issues/104206. -class SelectedContent { +@immutable +class SelectedContent with Diagnosticable { /// Creates a selected content object. /// /// Only supports plain text. - const SelectedContent({required this.plainText}); + const SelectedContent({ + required this.plainText, + }); /// The selected content in plain text format. final String plainText; + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(StringProperty('plainText', plainText)); + } } /// A mixin that can be selected by users when under a [SelectionArea] widget. @@ -138,7 +237,7 @@ class SelectedContent { /// {@macro flutter.rendering.SelectionHandler} /// /// See also: -/// * [SelectionArea], which provides an overview of selection system. +/// * [SelectableRegion], which provides an overview of selection system. mixin Selectable implements SelectionHandler { /// {@macro flutter.rendering.RenderObject.getTransformTo} Matrix4 getTransformTo(RenderObject? ancestor); @@ -628,7 +727,7 @@ enum SelectionStatus { /// The positions in geometry are in local coordinates of the [SelectionHandler] /// or [Selectable]. @immutable -class SelectionGeometry { +class SelectionGeometry with Diagnosticable { /// Creates a selection geometry object. /// /// If any of the [startSelectionPoint] and [endSelectionPoint] is not null, @@ -728,6 +827,16 @@ class SelectionGeometry { hasContent, ); } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(DiagnosticsProperty('startSelectionPoint', startSelectionPoint)); + properties.add(DiagnosticsProperty('endSelectionPoint', endSelectionPoint)); + properties.add(IterableProperty('selectionRects', selectionRects)); + properties.add(EnumProperty('status', status)); + properties.add(DiagnosticsProperty('hasContent', hasContent)); + } } /// The geometry information of a selection point. diff --git a/packages/flutter/lib/src/rendering/sliver_persistent_header.dart b/packages/flutter/lib/src/rendering/sliver_persistent_header.dart index dc173cf875b..2e9b62c1cb6 100644 --- a/packages/flutter/lib/src/rendering/sliver_persistent_header.dart +++ b/packages/flutter/lib/src/rendering/sliver_persistent_header.dart @@ -162,7 +162,13 @@ abstract class RenderSliverPersistentHeader extends RenderSliver with RenderObje } bool _needsUpdateChild = true; + + /// The most recent `shrinkOffset` passed to [updateChild]. + double get lastShrinkOffset => _lastShrinkOffset; double _lastShrinkOffset = 0.0; + + /// The most recent `overlapsContent` passed to [updateChild]. + bool get lastOverlapsContent => _lastOverlapsContent; bool _lastOverlapsContent = false; /// Defines the parameters used to execute an [AsyncCallback] when a diff --git a/packages/flutter/lib/src/semantics/semantics.dart b/packages/flutter/lib/src/semantics/semantics.dart index 1934aa2b80c..2ddf3f8439b 100644 --- a/packages/flutter/lib/src/semantics/semantics.dart +++ b/packages/flutter/lib/src/semantics/semantics.dart @@ -49,6 +49,10 @@ typedef SetSelectionHandler = void Function(TextSelection selection); /// current text with the input `text`. typedef SetTextHandler = void Function(String text); +/// Signature for the [SemanticsAction.scrollToOffset] handlers to scroll the +/// scrollable container to the given `targetOffset`. +typedef ScrollToOffsetHandler = void Function(Offset targetOffset); + /// Signature for a handler of a [SemanticsAction]. /// /// Returned by [SemanticsConfiguration.getActionHandler]. @@ -1698,7 +1702,7 @@ class SemanticsProperties extends DiagnosticableTree { /// * Buttons must respond to tap/click events produced via keyboard shortcuts. /// * Text fields must become focused and editable, showing an on-screen /// keyboard, if necessary. - /// * Checkboxes, switches, and radio buttons must become togglable using + /// * Checkboxes, switches, and radio buttons must become toggleable using /// keyboard shortcuts. /// /// Focus behavior is specific to the platform and to the assistive technology @@ -2092,8 +2096,7 @@ class SemanticsNode with DiagnosticableTreeMixin { /// Visits the immediate children of this node. /// /// This function calls visitor for each immediate child until visitor returns - /// false. Returns true if all the visitor calls returned true, otherwise - /// returns false. + /// false. void visitChildren(SemanticsNodeVisitor visitor) { if (_children != null) { for (final SemanticsNode child in _children!) { @@ -3921,6 +3924,29 @@ class SemanticsConfiguration { _onScrollDown = value; } + /// The handler for [SemanticsAction.scrollToOffset]. + /// + /// This handler is only called on iOS by UIKit, when the iOS focus engine + /// switches its focus to an item too close to a scrollable edge of a + /// scrollable container, to make sure the focused item is always fully + /// visible. + /// + /// The callback, if not `null`, should typically set the scroll offset of + /// the associated scrollable container to the given `targetOffset` without + /// animation as it is already animated by the caller: the iOS focus engine + /// invokes [onScrollToOffset] every frame during the scroll animation with + /// animated scroll offset values. + ScrollToOffsetHandler? get onScrollToOffset => _onScrollToOffset; + ScrollToOffsetHandler? _onScrollToOffset; + set onScrollToOffset(ScrollToOffsetHandler? value) { + assert(value != null); + _addAction(SemanticsAction.scrollToOffset, (Object? args) { + final Float64List list = args! as Float64List; + value!(Offset(list[0], list[1])); + }); + _onScrollToOffset = value; + } + /// The handler for [SemanticsAction.increase]. /// /// This is a request to increase the value represented by the widget. For diff --git a/packages/flutter/lib/src/services/haptic_feedback.dart b/packages/flutter/lib/src/services/haptic_feedback.dart index e3aad6c28e3..7c0fa8af55d 100644 --- a/packages/flutter/lib/src/services/haptic_feedback.dart +++ b/packages/flutter/lib/src/services/haptic_feedback.dart @@ -9,6 +9,10 @@ import 'system_channels.dart'; /// /// This API is intentionally terse since it calls default platform behavior. It /// is not suitable for precise control of the system's haptic feedback module. +/// +/// See also: +/// +/// * [Human Interface Haptics Guidelines](https://developer.apple.com/design/human-interface-guidelines/playing-haptics) abstract final class HapticFeedback { /// Provides vibration haptic feedback to the user for a short duration. /// @@ -28,6 +32,12 @@ abstract final class HapticFeedback { /// below 10. /// /// On Android, this uses `HapticFeedbackConstants.VIRTUAL_KEY`. + /// + /// {@template flutter.services.HapticFeedback.impact} + /// See also: + /// + /// * [Human Interface Selection Playing Impact Haptic](https://developer.apple.com/design/human-interface-guidelines/playing-haptics#Impact) + /// {@endtemplate} static Future lightImpact() async { await SystemChannels.platform.invokeMethod( 'HapticFeedback.vibrate', @@ -42,6 +52,8 @@ abstract final class HapticFeedback { /// below 10. /// /// On Android, this uses `HapticFeedbackConstants.KEYBOARD_TAP`. + /// + /// {@macro flutter.services.HapticFeedback.impact} static Future mediumImpact() async { await SystemChannels.platform.invokeMethod( 'HapticFeedback.vibrate', @@ -57,6 +69,8 @@ abstract final class HapticFeedback { /// /// On Android, this uses `HapticFeedbackConstants.CONTEXT_CLICK` on API levels /// 23 and above. This call has no effects on Android API levels below 23. + /// + /// {@macro flutter.services.HapticFeedback.impact} static Future heavyImpact() async { await SystemChannels.platform.invokeMethod( 'HapticFeedback.vibrate', @@ -70,6 +84,10 @@ abstract final class HapticFeedback { /// This call has no effects on iOS versions below 10. /// /// On Android, this uses `HapticFeedbackConstants.CLOCK_TICK`. + /// + /// See also: + /// + /// * [Human Interface Selection Playing Selection Haptics](https://developer.apple.com/design/human-interface-guidelines/playing-haptics#Selection) static Future selectionClick() async { await SystemChannels.platform.invokeMethod( 'HapticFeedback.vibrate', diff --git a/packages/flutter/lib/src/services/scribe.dart b/packages/flutter/lib/src/services/scribe.dart new file mode 100644 index 00000000000..4a17271e95e --- /dev/null +++ b/packages/flutter/lib/src/services/scribe.dart @@ -0,0 +1,143 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/foundation.dart'; + +import 'message_codec.dart'; +import 'system_channels.dart'; + +/// An interface into Android's stylus handwriting text input. +/// +/// Allows handwriting directly on top of a text input using a stylus. +/// +/// See also: +/// +/// * [EditableText.stylusHandwritingEnabled], which controls whether Flutter's +/// built-in text fields support handwriting input. +/// * [SystemChannels.scribe], which is the [MethodChannel] used by this +/// class, and which has a list of the methods that this class handles. +/// * , +/// which is the Android documentation explaining the Scribe feature. +abstract final class Scribe { + static const MethodChannel _channel = SystemChannels.scribe; + + /// A convenience method to check if the device currently supports Scribe + /// stylus handwriting input. + /// + /// Call this each time before calling [startStylusHandwriting] to make sure + /// it's available. + /// + /// {@tool snippet} + /// This example shows using [isFeatureAvailable] to confirm that + /// [startStylusHandwriting] can be called. + /// + /// ```dart + /// if (!await Scribe.isFeatureAvailable()) { + /// // The device doesn't support stylus input right now, or maybe at all. + /// return; + /// } + /// + /// // Scribe is supported, so start it. + /// Scribe.startStylusHandwriting(); + /// ``` + /// {@end-tool} + /// + /// See also: + /// + /// * [isStylusHandwritingAvailable], which is similar, but throws an error + /// when called by an unsupported API level. It directly corresponds to the + /// underlying Android API + /// . + /// * [EditableText.stylusHandwritingEnabled], which controls whether + /// Flutter's built-in text fields support handwriting input. + static Future isFeatureAvailable() async { + final bool? result = await _channel.invokeMethod( + 'Scribe.isFeatureAvailable', + ); + + if (result == null) { + throw FlutterError('MethodChannel.invokeMethod unexpectedly returned null.'); + } + + return result; + } + + /// Returns true if the InputMethodManager supports Scribe stylus handwriting + /// input, false otherwise. + /// + /// Call this each time before calling [startStylusHandwriting] to make sure + /// it's available. + /// + /// Supported on Android API 34 and above. If called by an unsupported API + /// level, a [PlatformException] will be thrown. To avoid error handling, use + /// the convenience method [isFeatureAvailable] instead. + /// + /// {@tool snippet} + /// This example shows using [isStylusHandwritingAvailable] to confirm that + /// [startStylusHandwriting] can be called. + /// + /// ```dart + /// try { + /// if (!await Scribe.isStylusHandwritingAvailable()) { + /// // If isStylusHandwritingAvailable returns false then the device's API level + /// // supports Scribe, but for some other reason it's not able to accept stylus + /// // input right now. + /// return; + /// } + /// } on PlatformException catch (exception) { + /// if (exception.message == 'Requires API level 34 or higher.') { + /// // The device's API level is too low to support Scribe. + /// return; + /// } + /// // Any other exception is unexpected and should not be caught here. + /// rethrow; + /// } + /// + /// // Scribe is supported, so start it. + /// Scribe.startStylusHandwriting(); + /// ``` + /// {@end-tool} + /// + /// See also: + /// + /// * , + /// which is the corresponding API on Android that this method attempts to + /// mirror. + static Future isStylusHandwritingAvailable() async { + final bool? result = await _channel.invokeMethod( + 'Scribe.isStylusHandwritingAvailable', + ); + + if (result == null) { + throw FlutterError('MethodChannel.invokeMethod unexpectedly returned null.'); + } + + return result; + } + + /// Tell Android to begin receiving stylus handwriting input. + /// + /// This is typically called after detecting a [PointerDownEvent] from a + /// [PointerDeviceKind.stylus] on an active text field, indicating the start + /// of stylus handwriting input. If there is no active [TextInputConnection], + /// the call will be ignored. + /// + /// Call [isFeatureAvailable] each time before calling this to make sure that + /// stylus handwriting input is supported and available. + /// + /// Supported on Android API 33 and above. + /// + /// See also: + /// + /// * , + /// which is the corresponding API on Android that this method attempts to + /// mirror. + /// * [EditableText.stylusHandwritingEnabled], which controls whether + /// Flutter's built-in text fields support handwriting input. + static Future startStylusHandwriting() { + return _channel.invokeMethod( + 'Scribe.startStylusHandwriting', + ); + } +} diff --git a/packages/flutter/lib/src/services/system_channels.dart b/packages/flutter/lib/src/services/system_channels.dart index d310abbb6da..14bb8ae4638 100644 --- a/packages/flutter/lib/src/services/system_channels.dart +++ b/packages/flutter/lib/src/services/system_channels.dart @@ -277,6 +277,35 @@ abstract final class SystemChannels { JSONMethodCodec(), ); + /// A [MethodChannel] for handling Android Scribe stylus handwriting input. + /// + /// Android's Scribe feature allows writing directly on top of a text input + /// using a stylus. + /// + /// The following methods are defined for this channel: + /// + /// * `Scribe.startStylusHandwriting`: Indicates that stylus input has been + /// detected and Android should start handwriting input. + /// * `Scribe.isStylusHandwritingAvailable`: Returns a boolean representing + /// whether or not the device currently supports accepting stylus handwriting + /// input. Throws if the device's API level is not sufficient. + /// * `Scribe.isFeatureAvailable`: Returns a boolean representing whether or + /// not the device currently supports accepting stylus handwriting input. + /// Returns false and does not throw if the device's API level is not + /// sufficient. + /// + /// See also: + /// + /// * [Scribe], which uese this channel. + /// * [ScribbleClient], which implements the iOS version of this feature, + /// [Scribble](https://support.apple.com/guide/ipad/enter-text-with-scribble-ipad355ab2a7/ipados). + /// * , + /// which is the Android documentation explaining the Scribe feature. + static const MethodChannel scribe = OptionalMethodChannel( + 'flutter/scribe', + JSONMethodCodec(), + ); + /// A [MethodChannel] for handling spell check for text input. /// /// This channel exposes the spell check framework for supported platforms. diff --git a/packages/flutter/lib/src/services/text_input.dart b/packages/flutter/lib/src/services/text_input.dart index eb8d91a5426..a8c0bf748c2 100644 --- a/packages/flutter/lib/src/services/text_input.dart +++ b/packages/flutter/lib/src/services/text_input.dart @@ -194,14 +194,24 @@ class TextInputType { /// Prevent the OS from showing the on-screen virtual keyboard. static const TextInputType none = TextInputType._(10); + /// Optimized for web searches. + /// + /// Requests a keyboard that includes keys useful for web searches as well as URLs. + /// + /// On iOS, requests a default keyboard with ready access to the "." key. In contrast to + /// [url], a space bar is available. + /// + /// On Android this is remapped to the [url] keyboard type as it always shows a space bar. + static const TextInputType webSearch = TextInputType._(11); + /// All possible enum values. static const List values = [ - text, multiline, number, phone, datetime, emailAddress, url, visiblePassword, name, streetAddress, none, + text, multiline, number, phone, datetime, emailAddress, url, visiblePassword, name, streetAddress, none, webSearch, ]; // Corresponding string name for each of the [values]. static const List _names = [ - 'text', 'multiline', 'number', 'phone', 'datetime', 'emailAddress', 'url', 'visiblePassword', 'name', 'address', 'none', + 'text', 'multiline', 'number', 'phone', 'datetime', 'emailAddress', 'url', 'visiblePassword', 'name', 'address', 'none', 'webSearch', ]; // Enum value name, this is what enum.toString() would normally return. @@ -1056,7 +1066,12 @@ enum SelectionChangedCause { /// of text. drag, - /// The user used iPadOS 14+ Scribble to change the selection. + // TODO(justinmc): Rename this to stylusHandwriting. + // https://github.com/flutter/flutter/issues/159223 + /// The user used stylus handwriting to change the selection. + /// + /// Currently, this is only supported on iPadOS 14+ via the Scribble feature, + /// or on Android API 34+ via the Scribe feature. scribble, } @@ -1252,9 +1267,13 @@ mixin TextInputClient { void performSelector(String selectorName) {} } -/// An interface to receive focus from the engine. +/// An interface into iOS's stylus handwriting text input. /// -/// This is currently only used to handle UIIndirectScribbleInteraction. +/// See also: +/// +/// * [Scribe], which provides similar functionality for Android. +/// * [UIIndirectScribbleInteraction](https://developer.apple.com/documentation/uikit/uiindirectscribbleinteraction), +/// which is iOS's API for Scribble. abstract class ScribbleClient { /// A unique identifier for this element. String get elementIdentifier; diff --git a/packages/flutter/lib/src/web.dart b/packages/flutter/lib/src/web.dart index 9bfb3e34971..05de1572fab 100644 --- a/packages/flutter/lib/src/web.dart +++ b/packages/flutter/lib/src/web.dart @@ -67,6 +67,7 @@ extension type DOMTokenList._(JSObject _) implements JSObject { extension type Element._(JSObject _) implements Node, JSObject { external DOMTokenList get classList; external void append(JSAny nodes); + external void remove(); } extension type Event._(JSObject _) implements JSObject {} @@ -83,6 +84,7 @@ extension type HTMLElement._(JSObject _) implements Element, JSObject { external String get innerText; external set innerText(String value); external CSSStyleDeclaration get style; + external HTMLElement cloneNode(bool deep); } extension type HTMLHeadElement._(JSObject _) implements HTMLElement, JSObject {} @@ -91,6 +93,22 @@ extension type HTMLStyleElement._(JSObject _) implements HTMLElement, JSObject { external CSSStyleSheet? get sheet; } +extension type HTMLImageElement._(JSObject _) implements HTMLElement, JSObject { + external String get src; + external set src(String value); + external num get naturalWidth; + external num get naturalHeight; + external JSPromise decode(); +} + +extension type HTMLCanvasElement._(JSObject _) implements HTMLElement, JSObject { + external int get width; + external set width(int value); + external int get height; + external set height(int value); + external String toDataURL(); +} + extension type MediaQueryList._(JSObject _) implements EventTarget, JSObject { external bool get matches; } @@ -120,6 +138,7 @@ extension type Window._(JSObject _) implements EventTarget, JSObject { external Navigator get navigator; external MediaQueryList matchMedia(String query); external Selection? getSelection(); + external String get origin; } extension type XMLHttpRequest._(JSObject _) diff --git a/packages/flutter/lib/src/widgets/_platform_selectable_region_context_menu_web.dart b/packages/flutter/lib/src/widgets/_platform_selectable_region_context_menu_web.dart index 5de83bb309f..e18e41187f8 100644 --- a/packages/flutter/lib/src/widgets/_platform_selectable_region_context_menu_web.dart +++ b/packages/flutter/lib/src/widgets/_platform_selectable_region_context_menu_web.dart @@ -14,7 +14,7 @@ import 'platform_view.dart'; import 'selection_container.dart'; const String _viewType = 'Browser__WebContextMenuViewType__'; -const String _kClassName = 'web-electable-region-context-menu'; +const String _kClassName = 'web-selectable-region-context-menu'; // These css rules hides the dom element with the class name. const String _kClassSelectionRule = '.$_kClassName::selection { background: transparent; }'; const String _kClassRule = ''' diff --git a/packages/flutter/lib/src/widgets/_web_image_io.dart b/packages/flutter/lib/src/widgets/_web_image_io.dart new file mode 100644 index 00000000000..00236295938 --- /dev/null +++ b/packages/flutter/lib/src/widgets/_web_image_io.dart @@ -0,0 +1,50 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import '../painting/_web_image_info_io.dart'; +import 'basic.dart'; +import 'framework.dart'; + +/// A [Widget] that displays an image that is backed by an element. +class RawWebImage extends StatelessWidget { + /// Creates a [RawWebImage]. + RawWebImage({ + super.key, + required this.image, + this.debugImageLabel, + this.width, + this.height, + this.fit, + this.alignment = Alignment.center, + this.matchTextDirection = false, + }) { + throw UnsupportedError('Cannot create a $RawWebImage when not running on the web'); + } + + /// The underlying `` element to be displayed. + final WebImageInfo image; + + /// A debug label explaining the image. + final String? debugImageLabel; + + /// The requested width for this widget. + final double? width; + + /// The requested height for this widget. + final double? height; + + /// How the `` should be inscribed in the box constraining it. + final BoxFit? fit; + + /// How the image should be aligned in the box constraining it. + final AlignmentGeometry alignment; + + /// Whether or not the alignment of the image should match the text direction. + final bool matchTextDirection; + + @override + Widget build(BuildContext context) { + throw UnsupportedError('It is impossible to instantiate a RawWebImage when not running on the web'); + } +} diff --git a/packages/flutter/lib/src/widgets/_web_image_web.dart b/packages/flutter/lib/src/widgets/_web_image_web.dart new file mode 100644 index 00000000000..ae7af6c42f4 --- /dev/null +++ b/packages/flutter/lib/src/widgets/_web_image_web.dart @@ -0,0 +1,382 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:ui_web' as ui_web; + +import 'package:flutter/foundation.dart'; + +import '../painting/_web_image_info_web.dart'; +import '../rendering/box.dart'; +import '../rendering/shifted_box.dart'; +import '../web.dart' as web; +import 'basic.dart'; +import 'framework.dart'; +import 'platform_view.dart'; + +/// Displays an `` element with `src` set to [src]. +class ImgElementPlatformView extends StatelessWidget { + /// Creates a platform view backed with an `` element. + ImgElementPlatformView(this.src, {super.key}) { + if (!_registered) { + _register(); + } + } + + static const String _viewType = 'Flutter__ImgElementImage__'; + static bool _registered = false; + + static void _register() { + assert(!_registered); + _registered = true; + ui_web.platformViewRegistry.registerViewFactory(_viewType, (int viewId, + {Object? params}) { + final Map paramsMap = params! as Map; + // Create a new element. The browser is able to display the image + // without fetching it over the network again. + final web.HTMLImageElement img = + web.document.createElement('img') as web.HTMLImageElement; + img.src = paramsMap['src']! as String; + return img; + }); + } + + /// The `src` URL for the `` tag. + final String? src; + + @override + Widget build(BuildContext context) { + if (src == null) { + return const SizedBox.expand(); + } + return HtmlElementView( + viewType: _viewType, + creationParams: {'src': src}, + ); + } +} + +/// A widget which displays and lays out an underlying `` platform view. +class RawWebImage extends SingleChildRenderObjectWidget { + /// Creates a [RawWebImage]. + RawWebImage({ + super.key, + required this.image, + this.debugImageLabel, + this.width, + this.height, + this.fit, + this.alignment = Alignment.center, + this.matchTextDirection = false, + }) : super(child: ImgElementPlatformView(image.htmlImage.src)); + + /// The underlying `` element to be displayed. + final WebImageInfo image; + + /// A debug label explaining the image. + final String? debugImageLabel; + + /// The requested width for this widget. + final double? width; + + /// The requested height for this widget. + final double? height; + + /// How the `` should be inscribed in the box constraining it. + final BoxFit? fit; + + /// How the image should be aligned in the box constraining it. + final AlignmentGeometry alignment; + + /// Whether or not the alignment of the image should match the text direction. + final bool matchTextDirection; + + @override + RenderObject createRenderObject(BuildContext context) { + return RenderWebImage( + image: image.htmlImage, + width: width, + height: height, + fit: fit, + alignment: alignment, + matchTextDirection: matchTextDirection, + textDirection: matchTextDirection || alignment is! Alignment + ? Directionality.of(context) + : null, + ); + } + + @override + void updateRenderObject(BuildContext context, RenderWebImage renderObject) { + renderObject + ..image = image.htmlImage + ..width = width + ..height = height + ..fit = fit + ..alignment = alignment + ..matchTextDirection = matchTextDirection + ..textDirection = matchTextDirection || alignment is! Alignment + ? Directionality.of(context) + : null; + } +} + +/// Lays out and positions the child `` element similarly to [RenderImage]. +class RenderWebImage extends RenderShiftedBox { + /// Creates a new [RenderWebImage]. + RenderWebImage({ + RenderBox? child, + required web.HTMLImageElement image, + double? width, + double? height, + BoxFit? fit, + AlignmentGeometry alignment = Alignment.center, + bool matchTextDirection = false, + TextDirection? textDirection, + }) : _image = image, + _width = width, + _height = height, + _fit = fit, + _alignment = alignment, + _matchTextDirection = matchTextDirection, + _textDirection = textDirection, + super(child); + + Alignment? _resolvedAlignment; + bool? _flipHorizontally; + + void _resolve() { + if (_resolvedAlignment != null) { + return; + } + _resolvedAlignment = alignment.resolve(textDirection); + _flipHorizontally = + matchTextDirection && textDirection == TextDirection.rtl; + } + + void _markNeedResolution() { + _resolvedAlignment = null; + _flipHorizontally = null; + markNeedsPaint(); + } + + /// Whether to paint the image in the direction of the [TextDirection]. + /// + /// If this is true, then in [TextDirection.ltr] contexts, the image will be + /// drawn with its origin in the top left (the "normal" painting direction for + /// images); and in [TextDirection.rtl] contexts, the image will be drawn with + /// a scaling factor of -1 in the horizontal direction so that the origin is + /// in the top right. + /// + /// This is occasionally used with images in right-to-left environments, for + /// images that were designed for left-to-right locales. Be careful, when + /// using this, to not flip images with integral shadows, text, or other + /// effects that will look incorrect when flipped. + /// + /// If this is set to true, [textDirection] must not be null. + bool get matchTextDirection => _matchTextDirection; + bool _matchTextDirection; + set matchTextDirection(bool value) { + if (value == _matchTextDirection) { + return; + } + _matchTextDirection = value; + _markNeedResolution(); + } + + /// The text direction with which to resolve [alignment]. + /// + /// This may be changed to null, but only after the [alignment] and + /// [matchTextDirection] properties have been changed to values that do not + /// depend on the direction. + TextDirection? get textDirection => _textDirection; + TextDirection? _textDirection; + set textDirection(TextDirection? value) { + if (_textDirection == value) { + return; + } + _textDirection = value; + _markNeedResolution(); + } + + /// The image to display. + web.HTMLImageElement get image => _image; + web.HTMLImageElement _image; + set image(web.HTMLImageElement value) { + if (value == _image) { + return; + } + // If we get a clone of our image, it's the same underlying native data - + // return early. + if (value.src == _image.src) { + return; + } + final bool sizeChanged = _image.naturalWidth != value.naturalWidth || + _image.naturalHeight != value.naturalHeight; + _image = value; + markNeedsPaint(); + if (sizeChanged && (_width == null || _height == null)) { + markNeedsLayout(); + } + } + + /// If non-null, requires the image to have this width. + /// + /// If null, the image will pick a size that best preserves its intrinsic + /// aspect ratio. + double? get width => _width; + double? _width; + set width(double? value) { + if (value == _width) { + return; + } + _width = value; + markNeedsLayout(); + } + + /// If non-null, require the image to have this height. + /// + /// If null, the image will pick a size that best preserves its intrinsic + /// aspect ratio. + double? get height => _height; + double? _height; + set height(double? value) { + if (value == _height) { + return; + } + _height = value; + markNeedsLayout(); + } + + /// How to inscribe the image into the space allocated during layout. + /// + /// The default varies based on the other fields. See the discussion at + /// [paintImage]. + BoxFit? get fit => _fit; + BoxFit? _fit; + set fit(BoxFit? value) { + if (value == _fit) { + return; + } + _fit = value; + markNeedsPaint(); + } + + /// How to align the image within its bounds. + /// + /// If this is set to a text-direction-dependent value, [textDirection] must + /// not be null. + AlignmentGeometry get alignment => _alignment; + AlignmentGeometry _alignment; + set alignment(AlignmentGeometry value) { + if (value == _alignment) { + return; + } + _alignment = value; + _markNeedResolution(); + } + + /// Find a size for the render image within the given constraints. + /// + /// - The dimensions of the RenderImage must fit within the constraints. + /// - The aspect ratio of the RenderImage matches the intrinsic aspect + /// ratio of the image. + /// - The RenderImage's dimension are maximal subject to being smaller than + /// the intrinsic size of the image. + Size _sizeForConstraints(BoxConstraints constraints) { + // Folds the given |width| and |height| into |constraints| so they can all + // be treated uniformly. + constraints = BoxConstraints.tightFor( + width: _width, + height: _height, + ).enforce(constraints); + + return constraints.constrainSizeAndAttemptToPreserveAspectRatio(Size( + _image.naturalWidth.toDouble(), + _image.naturalHeight.toDouble(), + )); + } + + @override + double computeMinIntrinsicWidth(double height) { + assert(height >= 0.0); + if (_width == null && _height == null) { + return 0.0; + } + return _sizeForConstraints(BoxConstraints.tightForFinite(height: height)) + .width; + } + + @override + double computeMaxIntrinsicWidth(double height) { + assert(height >= 0.0); + return _sizeForConstraints(BoxConstraints.tightForFinite(height: height)) + .width; + } + + @override + double computeMinIntrinsicHeight(double width) { + assert(width >= 0.0); + if (_width == null && _height == null) { + return 0.0; + } + return _sizeForConstraints(BoxConstraints.tightForFinite(width: width)) + .height; + } + + @override + double computeMaxIntrinsicHeight(double width) { + assert(width >= 0.0); + return _sizeForConstraints(BoxConstraints.tightForFinite(width: width)) + .height; + } + + @override + bool hitTestSelf(Offset position) => true; + + @override + @protected + Size computeDryLayout(covariant BoxConstraints constraints) { + return _sizeForConstraints(constraints); + } + + @override + void performLayout() { + _resolve(); + assert(_resolvedAlignment != null); + assert(_flipHorizontally != null); + size = _sizeForConstraints(constraints); + + if (child == null) { + return; + } + + final Size inputSize = + Size(image.naturalWidth.toDouble(), image.naturalHeight.toDouble()); + fit ??= BoxFit.scaleDown; + final FittedSizes fittedSizes = applyBoxFit(fit!, inputSize, size); + final Size childSize = fittedSizes.destination; + child!.layout(BoxConstraints.tight(childSize)); + final double halfWidthDelta = (size.width - childSize.width) / 2.0; + final double halfHeightDelta = (size.height - childSize.height) / 2.0; + final double dx = halfWidthDelta + + (_flipHorizontally! ? -_resolvedAlignment!.x : _resolvedAlignment!.x) * + halfWidthDelta; + final double dy = + halfHeightDelta + _resolvedAlignment!.y * halfHeightDelta; + final BoxParentData childParentData = child!.parentData! as BoxParentData; + childParentData.offset = Offset(dx, dy); + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(DiagnosticsProperty('image', image)); + properties.add(DoubleProperty('width', width, defaultValue: null)); + properties.add(DoubleProperty('height', height, defaultValue: null)); + properties.add(EnumProperty('fit', fit, defaultValue: null)); + properties.add(DiagnosticsProperty( + 'alignment', alignment, + defaultValue: null)); + } +} diff --git a/packages/flutter/lib/src/widgets/animated_scroll_view.dart b/packages/flutter/lib/src/widgets/animated_scroll_view.dart index e32073164fa..c61ead4cbee 100644 --- a/packages/flutter/lib/src/widgets/animated_scroll_view.dart +++ b/packages/flutter/lib/src/widgets/animated_scroll_view.dart @@ -299,7 +299,7 @@ class AnimatedList extends _AnimatedScrollView { /// [AnimatedList] item input handlers can also refer to their [AnimatedListState] /// with the static [AnimatedList.of] method. class AnimatedListState extends _AnimatedScrollViewState { - + @protected @override Widget build(BuildContext context) { return _wrap( @@ -508,7 +508,7 @@ class AnimatedGrid extends _AnimatedScrollView { /// [AnimatedGrid] item input handlers can also refer to their [AnimatedGridState] /// with the static [AnimatedGrid.of] method. class AnimatedGridState extends _AnimatedScrollViewState { - + @protected @override Widget build(BuildContext context) { return _wrap( @@ -1040,7 +1040,7 @@ class SliverAnimatedList extends _SliverAnimatedMultiBoxAdaptor { /// [SliverAnimatedList] item input handlers can also refer to their /// [SliverAnimatedListState] with the static [SliverAnimatedList.of] method. class SliverAnimatedListState extends _SliverAnimatedMultiBoxAdaptorState { - + @protected @override Widget build(BuildContext context) { return SliverList( @@ -1187,7 +1187,7 @@ class SliverAnimatedGrid extends _SliverAnimatedMultiBoxAdaptor { /// [SliverAnimatedGrid] item input handlers can also refer to their /// [SliverAnimatedGridState] with the static [SliverAnimatedGrid.of] method. class SliverAnimatedGridState extends _SliverAnimatedMultiBoxAdaptorState { - + @protected @override Widget build(BuildContext context) { return SliverGrid( diff --git a/packages/flutter/lib/src/widgets/app.dart b/packages/flutter/lib/src/widgets/app.dart index 88720bd71c0..872f0319c3f 100644 --- a/packages/flutter/lib/src/widgets/app.dart +++ b/packages/flutter/lib/src/widgets/app.dart @@ -341,7 +341,8 @@ class WidgetsApp extends StatefulWidget { this.showSemanticsDebugger = false, this.debugShowWidgetInspector = false, this.debugShowCheckedModeBanner = true, - this.inspectorSelectButtonBuilder, + this.exitWidgetSelectionButtonBuilder, + this.moveExitWidgetSelectionButtonBuilder, this.shortcuts, this.actions, this.restorationScopeId, @@ -439,7 +440,8 @@ class WidgetsApp extends StatefulWidget { this.showSemanticsDebugger = false, this.debugShowWidgetInspector = false, this.debugShowCheckedModeBanner = true, - this.inspectorSelectButtonBuilder, + this.exitWidgetSelectionButtonBuilder, + this.moveExitWidgetSelectionButtonBuilder, this.shortcuts, this.actions, this.restorationScopeId, @@ -1026,13 +1028,20 @@ class WidgetsApp extends StatefulWidget { /// debug mode. final bool debugShowWidgetInspector; - /// Builds the widget the [WidgetInspector] uses to switch between view and - /// inspect modes. + /// Builds the widget the [WidgetInspector] uses to exit selection mode. /// - /// This lets [MaterialApp] to use a Material Design button to toggle the + /// This lets [MaterialApp] to use a Material Design button to exit the /// inspector select mode without requiring [WidgetInspector] to depend on the - /// material package. - final InspectorSelectButtonBuilder? inspectorSelectButtonBuilder; + /// Material package. + final ExitWidgetSelectionButtonBuilder? exitWidgetSelectionButtonBuilder; + + /// Builds the widget the [WidgetInspector] uses to move the exit selection + /// mode button. + /// + /// This lets [MaterialApp] to use a Material Design button to change the + /// alignment without requiring [WidgetInspector] to depend on the Material + /// package. + final MoveExitWidgetSelectionButtonBuilder? moveExitWidgetSelectionButtonBuilder; /// {@template flutter.widgets.widgetsApp.debugShowCheckedModeBanner} /// Turns on a little "DEBUG" banner in debug mode to indicate @@ -1755,7 +1764,8 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { builder: (BuildContext context, bool debugShowWidgetInspectorOverride, Widget? child) { if (widget.debugShowWidgetInspector || debugShowWidgetInspectorOverride) { return WidgetInspector( - selectButtonBuilder: widget.inspectorSelectButtonBuilder, + exitWidgetSelectionButtonBuilder: widget.exitWidgetSelectionButtonBuilder, + moveExitWidgetSelectionButtonBuilder: widget.moveExitWidgetSelectionButtonBuilder, child: child!, ); } diff --git a/packages/flutter/lib/src/widgets/autofill.dart b/packages/flutter/lib/src/widgets/autofill.dart index ab9a5663006..bedcf8328af 100644 --- a/packages/flutter/lib/src/widgets/autofill.dart +++ b/packages/flutter/lib/src/widgets/autofill.dart @@ -213,12 +213,14 @@ class AutofillGroupState extends State with AutofillScopeMixin { _clients.remove(autofillId); } + @protected @override void didChangeDependencies() { super.didChangeDependencies(); _isTopmostAutofillGroup = AutofillGroup.maybeOf(context) == null; } + @protected @override Widget build(BuildContext context) { return _AutofillScope( @@ -227,6 +229,7 @@ class AutofillGroupState extends State with AutofillScopeMixin { ); } + @protected @override void dispose() { super.dispose(); diff --git a/packages/flutter/lib/src/widgets/decorated_sliver.dart b/packages/flutter/lib/src/widgets/decorated_sliver.dart index d51af4812a6..c845d44176c 100644 --- a/packages/flutter/lib/src/widgets/decorated_sliver.dart +++ b/packages/flutter/lib/src/widgets/decorated_sliver.dart @@ -25,8 +25,6 @@ import 'image.dart'; /// /// Commonly used with [BoxDecoration]. /// -/// The [child] is not clipped. To clip a child to the shape of a particular -/// [ShapeDecoration], consider using a [ClipPath] widget. /// /// {@tool dartpad} /// This sample shows a radial gradient that draws a moon on a night sky: @@ -34,6 +32,20 @@ import 'image.dart'; /// ** See code in examples/api/lib/widgets/sliver/decorated_sliver.0.dart ** /// {@end-tool} /// +/// {@tool dartpad} +/// This example demonstrates how the [CustomScrollView.clipBehavior] +/// impacts a decorated sliver's appearance. +/// +/// The [Switch] determines whether clipping is enabled, and +/// the [Slider] adjusts the height of window. +/// +/// ** See code in examples/api/lib/widgets/sliver/decorated_sliver.1.dart ** +/// {@end-tool} +/// +/// This widget does not apply any additional clipping to its [child]. +/// To clip a child based on the [Decoration]'s shape, consider using +/// a [ClipPath] widget. +/// /// See also: /// /// * [DecoratedBox], the version of this class that works with RenderBox widgets. diff --git a/packages/flutter/lib/src/widgets/editable_text.dart b/packages/flutter/lib/src/widgets/editable_text.dart index 9ae6d0f6004..3bdc345778e 100644 --- a/packages/flutter/lib/src/widgets/editable_text.dart +++ b/packages/flutter/lib/src/widgets/editable_text.dart @@ -20,7 +20,7 @@ import 'dart:ui' as ui hide TextStyle; import 'package:characters/characters.dart' show CharacterRange, StringCharacters; import 'package:flutter/foundation.dart'; -import 'package:flutter/gestures.dart' show DragStartBehavior; +import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; @@ -880,7 +880,12 @@ class EditableText extends StatefulWidget { this.clipBehavior = Clip.hardEdge, this.restorationId, this.scrollBehavior, + @Deprecated( + 'Use `stylusHandwritingEnabled` instead. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) this.scribbleEnabled = true, + this.stylusHandwritingEnabled = defaultStylusHandwritingEnabled, this.enableIMEPersonalizedLearning = true, this.contentInsertionConfiguration, this.contextMenuBuilder, @@ -1735,8 +1740,33 @@ class EditableText extends StatefulWidget { /// /// Defaults to true. /// {@endtemplate} + @Deprecated( + 'Use `stylusHandwritingEnabled` instead. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) final bool scribbleEnabled; + /// {@template flutter.widgets.editableText.stylusHandwritingEnabled} + /// Whether this input supports stylus handwriting, where the user can write + /// directly on top of a field. + /// + /// Currently only the following devices are supported: + /// + /// * iPads running iOS 14 and above using an Apple Pencil. + /// * Android devices running API 34 and above and using an active stylus. + /// {@endtemplate} + /// + /// On Android, Scribe gestures are detected outside of [EditableText], + /// typically by [TextSelectionGestureDetectorBuilder]. This is handled + /// automatically in [TextField]. + /// + /// See also: + /// + /// * [ScribbleClient], which can be mixed into an arbitrary widget to + /// provide iOS Scribble functionality. + /// * [Scribe], which can be used to interact with Android Scribe directly. + final bool stylusHandwritingEnabled; + /// {@template flutter.widgets.editableText.selectionEnabled} /// Same as [enableInteractiveSelection]. /// @@ -1803,6 +1833,10 @@ class EditableText extends StatefulWidget { /// Autofill service. Enable the autofill service of your choice, and make /// sure there are available credentials associated with your app. /// + /// Specifying [InputDecoration.hintText] may also help autofill services + /// (like Samsung Pass) determine the expected content type of an input field, + /// although this is typically not required when autofillHints are present. + /// /// #### I called `TextInput.finishAutofillContext` but the autofill save /// prompt isn't showing /// @@ -1847,17 +1881,17 @@ class EditableText extends StatefulWidget { /// Flutter. final String? restorationId; - /// {@template flutter.widgets.shadow.scrollBehavior} + /// {@template flutter.widgets.editableText.scrollBehavior} /// A [ScrollBehavior] that will be applied to this widget individually. /// /// Defaults to null, wherein the inherited [ScrollBehavior] is copied and /// modified to alter the viewport decoration, like [Scrollbar]s. - /// {@endtemplate} /// /// [ScrollBehavior]s also provide [ScrollPhysics]. If an explicit /// [ScrollPhysics] is provided in [scrollPhysics], it will take precedence, /// followed by [scrollBehavior], and then the inherited ancestor /// [ScrollBehavior]. + /// {@endtemplate} /// /// The [ScrollBehavior] of the inherited [ScrollConfiguration] will be /// modified by default to only apply a [Scrollbar] if [maxLines] is greater @@ -1975,6 +2009,9 @@ class EditableText extends StatefulWidget { /// {@macro flutter.widgets.magnifier.intro} final TextMagnifierConfiguration magnifierConfiguration; + /// The default value for [stylusHandwritingEnabled]. + static const bool defaultStylusHandwritingEnabled = true; + bool get _userSelectionEnabled => enableInteractiveSelection && (!readOnly || !obscureText); /// Returns the [ContextMenuButtonItem]s representing the buttons in this @@ -2242,6 +2279,7 @@ class EditableText extends StatefulWidget { properties.add(DiagnosticsProperty>('autofillHints', autofillHints, defaultValue: null)); properties.add(DiagnosticsProperty('textHeightBehavior', textHeightBehavior, defaultValue: null)); properties.add(DiagnosticsProperty('scribbleEnabled', scribbleEnabled, defaultValue: true)); + properties.add(DiagnosticsProperty('stylusHandwritingEnabled', stylusHandwritingEnabled, defaultValue: defaultStylusHandwritingEnabled)); properties.add(DiagnosticsProperty('enableIMEPersonalizedLearning', enableIMEPersonalizedLearning, defaultValue: true)); properties.add(DiagnosticsProperty('enableInteractiveSelection', enableInteractiveSelection, defaultValue: true)); properties.add(DiagnosticsProperty('undoController', undoController, defaultValue: null)); @@ -2363,6 +2401,15 @@ class EditableTextState extends State with AutomaticKeepAliveClien Orientation? _lastOrientation; + bool get _stylusHandwritingEnabled { + // During the deprecation period, respect scribbleEnabled being explicitly + // set. + if (!widget.scribbleEnabled) { + return widget.scribbleEnabled; + } + return widget.stylusHandwritingEnabled; + } + late final AppLifecycleListener _appLifecycleListener; bool _justResumed = false; @@ -2979,6 +3026,7 @@ class EditableTextState extends State with AutomaticKeepAliveClien // State lifecycle: + @protected @override void initState() { super.initState(); @@ -3005,6 +3053,7 @@ class EditableTextState extends State with AutomaticKeepAliveClien // cursor) are supposed to run. bool _tickersEnabled = true; + @protected @override void didChangeDependencies() { super.didChangeDependencies(); @@ -3080,6 +3129,7 @@ class EditableTextState extends State with AutomaticKeepAliveClien } } + @protected @override void didUpdateWidget(EditableText oldWidget) { super.didUpdateWidget(oldWidget); @@ -3183,6 +3233,7 @@ class EditableTextState extends State with AutomaticKeepAliveClien } } + @protected @override void dispose() { _internalScrollController?.dispose(); @@ -4460,7 +4511,7 @@ class EditableTextState extends State with AutomaticKeepAliveClien _ScribbleCacheKey? _scribbleCacheKey; void _updateSelectionRects({bool force = false}) { - if (!widget.scribbleEnabled || defaultTargetPlatform != TargetPlatform.iOS) { + if (!_stylusHandwritingEnabled || defaultTargetPlatform != TargetPlatform.iOS) { return; } @@ -4636,6 +4687,9 @@ class EditableTextState extends State with AutomaticKeepAliveClien if (_selectionOverlay == null) { return false; } + if (_selectionOverlay!.toolbarIsVisible) { + return false; + } _liveTextInputStatus?.update(); clipboardStatus.update(); _selectionOverlay!.showToolbar(); @@ -4751,7 +4805,7 @@ class EditableTextState extends State with AutomaticKeepAliveClien @override void insertTextPlaceholder(Size size) { - if (!widget.scribbleEnabled) { + if (!_stylusHandwritingEnabled) { return; } @@ -4766,7 +4820,7 @@ class EditableTextState extends State with AutomaticKeepAliveClien @override void removeTextPlaceholder() { - if (!widget.scribbleEnabled || _placeholderLocation == -1) { + if (!_stylusHandwritingEnabled || _placeholderLocation == -1) { return; } @@ -5178,6 +5232,7 @@ class EditableTextState extends State with AutomaticKeepAliveClien EditableTextTapOutsideIntent: _makeOverridable(_EditableTextTapOutsideAction()), }; + @protected @override Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); @@ -5279,9 +5334,9 @@ class EditableTextState extends State with AutomaticKeepAliveClien onCut: _semanticsOnCut(controls), onPaste: _semanticsOnPaste(controls), child: _ScribbleFocusable( - focusNode: widget.focusNode, editableKey: _editableKey, - enabled: widget.scribbleEnabled, + enabled: _stylusHandwritingEnabled, + focusNode: widget.focusNode, updateSelectionRects: () { _openInputConnection(); _updateSelectionRects(force: true); diff --git a/packages/flutter/lib/src/widgets/form.dart b/packages/flutter/lib/src/widgets/form.dart index 525cd02b544..0fa2ed741b7 100644 --- a/packages/flutter/lib/src/widgets/form.dart +++ b/packages/flutter/lib/src/widgets/form.dart @@ -12,6 +12,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'basic.dart'; +import 'binding.dart'; import 'focus_manager.dart'; import 'focus_scope.dart'; import 'framework.dart'; @@ -250,24 +251,13 @@ class FormState extends State
{ void _register(FormFieldState field) { _fields.add(field); - if (widget.autovalidateMode == AutovalidateMode.onUnfocus) { - field._focusNode.addListener(() => _updateField(field)); - } } void _unregister(FormFieldState field) { _fields.remove(field); - if (widget.autovalidateMode == AutovalidateMode.onUnfocus) { - field._focusNode.removeListener(()=> _updateField(field)); - } - } - - void _updateField(FormFieldState field) { - if (!field._focusNode.hasFocus) { - _validate(); - } } + @protected @override Widget build(BuildContext context) { switch (widget.autovalidateMode) { @@ -364,10 +354,15 @@ class FormState extends State { final bool validateOnFocusChange = widget.autovalidateMode == AutovalidateMode.onUnfocus; for (final FormFieldState field in _fields) { - if (!validateOnFocusChange || !field._focusNode.hasFocus) { + final bool hasFocus = field._focusNode.hasFocus; + + if (!validateOnFocusChange || !hasFocus || (validateOnFocusChange && hasFocus)) { final bool isFieldValid = field.validate(); - hasError = !isFieldValid || hasError; - errorMessage += field.errorText ?? ''; + hasError |= !isFieldValid; + // Ensure that only the first error message gets announced to the user. + if (errorMessage.isEmpty) { + errorMessage = field.errorText ?? ''; + } if (invalidFields != null && !isFieldValid) { invalidFields.add(field); } @@ -671,24 +666,28 @@ class FormFieldState extends State> with RestorationMixin { @override String? get restorationId => widget.restorationId; + @protected @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(_errorText, 'error_text'); registerForRestoration(_hasInteractedByUser, 'has_interacted_by_user'); } + @protected @override void deactivate() { Form.maybeOf(context)?._unregister(this); super.deactivate(); } + @protected @override void initState() { super.initState(); _errorText = RestorableStringN(widget.forceErrorText); } + @protected @override void didUpdateWidget(FormField oldWidget) { super.didUpdateWidget(oldWidget); @@ -697,6 +696,26 @@ class FormFieldState extends State> with RestorationMixin { } } + @protected + @override + void didChangeDependencies() { + super.didChangeDependencies(); + switch (Form.maybeOf(context)?.widget.autovalidateMode) { + case AutovalidateMode.always: + WidgetsBinding.instance.addPostFrameCallback((_) { + // If the form is already validated, don't validate again. + if (widget.enabled && !hasError && !isValid) { + validate(); + } + }); + case AutovalidateMode.onUnfocus: + case AutovalidateMode.onUserInteraction: + case AutovalidateMode.disabled: + case null: + break; + } + } + @override void dispose() { _errorText.dispose(); @@ -705,6 +724,7 @@ class FormFieldState extends State> with RestorationMixin { super.dispose(); } + @protected @override Widget build(BuildContext context) { if (widget.enabled) { @@ -742,7 +762,6 @@ class FormFieldState extends State> with RestorationMixin { return widget.builder(this); } - } /// Used to configure the auto validation of [FormField] and [Form] widgets. diff --git a/packages/flutter/lib/src/widgets/framework.dart b/packages/flutter/lib/src/widgets/framework.dart index d62671075c2..86c51dd00d0 100644 --- a/packages/flutter/lib/src/widgets/framework.dart +++ b/packages/flutter/lib/src/widgets/framework.dart @@ -1495,6 +1495,9 @@ abstract class State with Diagnosticable { properties.add(ObjectFlagProperty('_widget', _widget, ifNull: 'no widget')); properties.add(ObjectFlagProperty('_element', _element, ifNull: 'not mounted')); } + + // If @protected State methods are added or removed, the analysis rule should be + // updated accordingly (dev/bots/custom_rules/protect_public_state_subtypes.dart) } /// A widget that has a child widget provided to it, instead of building a new @@ -2710,7 +2713,7 @@ final class BuildScope { } bool _debugAssertElementInScope(Element element, Element debugBuildRoot) { - final bool isInScope = element._debugIsDescsendantOf(debugBuildRoot) + final bool isInScope = element._debugIsDescendantOf(debugBuildRoot) || !element.debugIsActive; if (isInScope) { return true; @@ -3671,7 +3674,7 @@ abstract class Element extends DiagnosticableTree implements BuildContext { }); } - bool _debugIsDescsendantOf(Element target) { + bool _debugIsDescendantOf(Element target) { Element? element = this; while (element != null && element.depth > target.depth) { element = element._parent; @@ -5169,7 +5172,7 @@ abstract class Element extends DiagnosticableTree implements BuildContext { if (owner!._debugBuilding) { assert(owner!._debugCurrentBuildTarget != null); assert(owner!._debugStateLocked); - if (_debugIsDescsendantOf(owner!._debugCurrentBuildTarget!)) { + if (_debugIsDescendantOf(owner!._debugCurrentBuildTarget!)) { return true; } final List information = [ @@ -5379,18 +5382,13 @@ class _ElementDiagnosticableTreeNode extends DiagnosticableTreeNode { final bool stateful; @override - Map toJsonMap( - DiagnosticsSerializationDelegate delegate, { - bool fullDetails = true, - }) { - final Map json = super.toJsonMap(delegate, fullDetails: fullDetails,); + Map toJsonMap(DiagnosticsSerializationDelegate delegate) { + final Map json = super.toJsonMap(delegate); final Element element = value as Element; if (!element.debugIsDefunct) { json['widgetRuntimeType'] = element.widget.runtimeType.toString(); } - if (fullDetails) { - json['stateful'] = stateful; - } + json['stateful'] = stateful; return json; } } diff --git a/packages/flutter/lib/src/widgets/gesture_detector.dart b/packages/flutter/lib/src/widgets/gesture_detector.dart index ed69eb76314..1b6b1e1f24a 100644 --- a/packages/flutter/lib/src/widgets/gesture_detector.dart +++ b/packages/flutter/lib/src/widgets/gesture_detector.dart @@ -1405,6 +1405,7 @@ class RawGestureDetectorState extends State { Map? _recognizers = const {}; SemanticsGestureDelegate? _semantics; + @protected @override void initState() { super.initState(); @@ -1412,6 +1413,7 @@ class RawGestureDetectorState extends State { _syncAll(widget.gestures); } + @protected @override void didUpdateWidget(RawGestureDetector oldWidget) { super.didUpdateWidget(oldWidget); @@ -1486,6 +1488,7 @@ class RawGestureDetectorState extends State { semanticsGestureHandler!.validActions = actions; // will call _markNeedsSemanticsUpdate(), if required. } + @protected @override void dispose() { for (final GestureRecognizer recognizer in _recognizers!.values) { @@ -1538,6 +1541,7 @@ class RawGestureDetectorState extends State { _semantics!.assignSemantics(renderObject); } + @protected @override Widget build(BuildContext context) { Widget result = Listener( @@ -1556,6 +1560,7 @@ class RawGestureDetectorState extends State { return result; } + @protected @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); diff --git a/packages/flutter/lib/src/widgets/icon_data.dart b/packages/flutter/lib/src/widgets/icon_data.dart index d13ce978632..ca118126d1a 100644 --- a/packages/flutter/lib/src/widgets/icon_data.dart +++ b/packages/flutter/lib/src/widgets/icon_data.dart @@ -121,17 +121,8 @@ class IconDataProperty extends DiagnosticsProperty { }); @override - Map toJsonMap( - DiagnosticsSerializationDelegate delegate, { - bool fullDetails = true, - }) { - final Map json = super.toJsonMap( - delegate, - fullDetails: fullDetails, - ); - if (!fullDetails) { - return json; - } + Map toJsonMap(DiagnosticsSerializationDelegate delegate) { + final Map json = super.toJsonMap(delegate); if (value != null) { json['valueProperties'] = { 'codePoint': value!.codePoint, diff --git a/packages/flutter/lib/src/widgets/image.dart b/packages/flutter/lib/src/widgets/image.dart index 0bc17964333..f1a93fe1c3f 100644 --- a/packages/flutter/lib/src/widgets/image.dart +++ b/packages/flutter/lib/src/widgets/image.dart @@ -17,6 +17,8 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/semantics.dart'; +import '../painting/_web_image_info_io.dart' if (dart.library.js_util) '../painting/_web_image_info_web.dart'; +import '_web_image_io.dart' if (dart.library.js_util) '_web_image_web.dart'; import 'basic.dart'; import 'binding.dart'; import 'disposable_build_context.dart'; @@ -1287,28 +1289,45 @@ class _ImageState extends State with WidgetsBindingObserver { } } - Widget result = RawImage( - // Do not clone the image, because RawImage is a stateless wrapper. - // The image will be disposed by this state object when it is not needed - // anymore, such as when it is unmounted or when the image stream pushes - // a new image. - image: _imageInfo?.image, - debugImageLabel: _imageInfo?.debugLabel, - width: widget.width, - height: widget.height, - scale: _imageInfo?.scale ?? 1.0, - color: widget.color, - opacity: widget.opacity, - colorBlendMode: widget.colorBlendMode, - fit: widget.fit, - alignment: widget.alignment, - repeat: widget.repeat, - centerSlice: widget.centerSlice, - matchTextDirection: widget.matchTextDirection, - invertColors: _invertColors, - isAntiAlias: widget.isAntiAlias, - filterQuality: widget.filterQuality, - ); + late Widget result; + if (_imageInfo case final WebImageInfo webImage) { + // TODO(harryterkelsen): Support the remaining properties that are + // supported by `RawImage` but not `RawWebImage`. See the following issue + // above for a discussion of the missing properties and suggestions for + // how they can be implemented, https://github.com/flutter/flutter/issues/159565. + result = RawWebImage( + image: webImage, + debugImageLabel: _imageInfo?.debugLabel, + width: widget.width, + height: widget.height, + fit: widget.fit, + alignment: widget.alignment, + matchTextDirection: widget.matchTextDirection, + ); + } else { + result = RawImage( + // Do not clone the image, because RawImage is a stateless wrapper. + // The image will be disposed by this state object when it is not needed + // anymore, such as when it is unmounted or when the image stream pushes + // a new image. + image: _imageInfo?.image, + debugImageLabel: _imageInfo?.debugLabel, + width: widget.width, + height: widget.height, + scale: _imageInfo?.scale ?? 1.0, + color: widget.color, + opacity: widget.opacity, + colorBlendMode: widget.colorBlendMode, + fit: widget.fit, + alignment: widget.alignment, + repeat: widget.repeat, + centerSlice: widget.centerSlice, + matchTextDirection: widget.matchTextDirection, + invertColors: _invertColors, + isAntiAlias: widget.isAntiAlias, + filterQuality: widget.filterQuality, + ); + } if (!widget.excludeFromSemantics) { result = Semantics( diff --git a/packages/flutter/lib/src/widgets/implicit_animations.dart b/packages/flutter/lib/src/widgets/implicit_animations.dart index 1271f2478ea..7ec291966ec 100644 --- a/packages/flutter/lib/src/widgets/implicit_animations.dart +++ b/packages/flutter/lib/src/widgets/implicit_animations.dart @@ -369,6 +369,7 @@ abstract class ImplicitlyAnimatedWidgetState Animation get animation => _animation; late CurvedAnimation _animation = _createCurve(); + @protected @override void initState() { super.initState(); @@ -381,6 +382,7 @@ abstract class ImplicitlyAnimatedWidgetState didUpdateTweens(); } + @protected @override void didUpdateWidget(T oldWidget) { super.didUpdateWidget(oldWidget); @@ -405,6 +407,7 @@ abstract class ImplicitlyAnimatedWidgetState return CurvedAnimation(parent: _controller, curve: widget.curve); } + @protected @override void dispose() { _animation.dispose(); @@ -554,6 +557,7 @@ abstract class ImplicitlyAnimatedWidgetState /// [AnimatedWidgetBaseState] to iterate through the subclasses' widget's fields /// and animate them. abstract class AnimatedWidgetBaseState extends ImplicitlyAnimatedWidgetState { + @protected @override void initState() { super.initState(); diff --git a/packages/flutter/lib/src/widgets/list_wheel_scroll_view.dart b/packages/flutter/lib/src/widgets/list_wheel_scroll_view.dart index b14ad8fdcff..31fca1ab551 100644 --- a/packages/flutter/lib/src/widgets/list_wheel_scroll_view.dart +++ b/packages/flutter/lib/src/widgets/list_wheel_scroll_view.dart @@ -710,12 +710,7 @@ class ListWheelScrollView extends StatefulWidget { /// {@macro flutter.widgets.scrollable.restorationId} final String? restorationId; - /// {@macro flutter.widgets.shadow.scrollBehavior} - /// - /// [ScrollBehavior]s also provide [ScrollPhysics]. If an explicit - /// [ScrollPhysics] is provided in [physics], it will take precedence, - /// followed by [scrollBehavior], and then the inherited ancestor - /// [ScrollBehavior]. + /// {@macro flutter.widgets.scrollable.scrollBehavior} /// /// The [ScrollBehavior] of the inherited [ScrollConfiguration] will be /// modified by default to not apply a [Scrollbar]. diff --git a/packages/flutter/lib/src/widgets/navigator.dart b/packages/flutter/lib/src/widgets/navigator.dart index 0d33acebb0c..649f81791ae 100644 --- a/packages/flutter/lib/src/widgets/navigator.dart +++ b/packages/flutter/lib/src/widgets/navigator.dart @@ -3706,6 +3706,7 @@ class NavigatorState extends State with TickerProviderStateMixin, Res return true; } + @protected @override void initState() { super.initState(); @@ -3742,6 +3743,7 @@ class NavigatorState extends State with TickerProviderStateMixin, Res int get _nextPagelessRestorationScopeId => _rawNextPagelessRestorationScopeId.value++; + @protected @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(_rawNextPagelessRestorationScopeId, 'id'); @@ -3810,6 +3812,7 @@ class NavigatorState extends State with TickerProviderStateMixin, Res assert(() { _debugLocked = false; return true; }()); } + @protected @override void didToggleBucket(RestorationBucket? oldBucket) { super.didToggleBucket(oldBucket); @@ -3822,6 +3825,7 @@ class NavigatorState extends State with TickerProviderStateMixin, Res @override String? get restorationId => widget.restorationScopeId; + @protected @override void didChangeDependencies() { super.didChangeDependencies(); @@ -3915,6 +3919,7 @@ class NavigatorState extends State with TickerProviderStateMixin, Res } } + @protected @override void didUpdateWidget(Navigator oldWidget) { super.didUpdateWidget(oldWidget); @@ -3969,6 +3974,7 @@ class NavigatorState extends State with TickerProviderStateMixin, Res }()); } + @protected @override void deactivate() { for (final NavigatorObserver observer in _effectiveObservers) { @@ -3978,6 +3984,7 @@ class NavigatorState extends State with TickerProviderStateMixin, Res super.deactivate(); } + @protected @override void activate() { super.activate(); @@ -3988,6 +3995,7 @@ class NavigatorState extends State with TickerProviderStateMixin, Res } } + @protected @override void dispose() { assert(!_debugLocked); @@ -5646,6 +5654,7 @@ class NavigatorState extends State with TickerProviderStateMixin, Res return result; } + @protected @override Widget build(BuildContext context) { assert(!_debugLocked); diff --git a/packages/flutter/lib/src/widgets/nested_scroll_view.dart b/packages/flutter/lib/src/widgets/nested_scroll_view.dart index 439f8e46371..177e33fb380 100644 --- a/packages/flutter/lib/src/widgets/nested_scroll_view.dart +++ b/packages/flutter/lib/src/widgets/nested_scroll_view.dart @@ -313,12 +313,7 @@ class NestedScrollView extends StatefulWidget { /// {@macro flutter.widgets.scrollable.restorationId} final String? restorationId; - /// {@macro flutter.widgets.shadow.scrollBehavior} - /// - /// [ScrollBehavior]s also provide [ScrollPhysics]. If an explicit - /// [ScrollPhysics] is provided in [physics], it will take precedence, - /// followed by [scrollBehavior], and then the inherited ancestor - /// [ScrollBehavior]. + /// {@macro flutter.widgets.scrollable.scrollBehavior} /// /// The [ScrollBehavior] of the inherited [ScrollConfiguration] will be /// modified by default to not apply a [Scrollbar]. This is because the @@ -425,6 +420,7 @@ class NestedScrollViewState extends State { _NestedScrollCoordinator? _coordinator; + @protected @override void initState() { super.initState(); @@ -436,12 +432,14 @@ class NestedScrollViewState extends State { ); } + @protected @override void didChangeDependencies() { super.didChangeDependencies(); _coordinator!.setParent(widget.controller); } + @protected @override void didUpdateWidget(NestedScrollView oldWidget) { super.didUpdateWidget(oldWidget); @@ -450,6 +448,7 @@ class NestedScrollViewState extends State { } } + @protected @override void dispose() { _coordinator!.dispose(); @@ -476,6 +475,7 @@ class NestedScrollViewState extends State { } } + @protected @override Widget build(BuildContext context) { final ScrollPhysics scrollPhysics = widget.physics?.applyTo(const ClampingScrollPhysics()) diff --git a/packages/flutter/lib/src/widgets/overlay.dart b/packages/flutter/lib/src/widgets/overlay.dart index df6d776ac86..cbc26314dd2 100644 --- a/packages/flutter/lib/src/widgets/overlay.dart +++ b/packages/flutter/lib/src/widgets/overlay.dart @@ -604,6 +604,7 @@ class Overlay extends StatefulWidget { class OverlayState extends State with TickerProviderStateMixin { final List _entries = []; + @protected @override void initState() { super.initState(); @@ -808,6 +809,7 @@ class OverlayState extends State with TickerProviderStateMixin { }); } + @protected @override Widget build(BuildContext context) { // This list is filled backwards and then reversed below before @@ -842,6 +844,7 @@ class OverlayState extends State with TickerProviderStateMixin { ); } + @protected @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); diff --git a/packages/flutter/lib/src/widgets/page_view.dart b/packages/flutter/lib/src/widgets/page_view.dart index d1ea02483fb..dcb5f295a24 100644 --- a/packages/flutter/lib/src/widgets/page_view.dart +++ b/packages/flutter/lib/src/widgets/page_view.dart @@ -839,12 +839,7 @@ class PageView extends StatefulWidget { /// Defaults to [HitTestBehavior.opaque]. final HitTestBehavior hitTestBehavior; - /// {@macro flutter.widgets.shadow.scrollBehavior} - /// - /// [ScrollBehavior]s also provide [ScrollPhysics]. If an explicit - /// [ScrollPhysics] is provided in [physics], it will take precedence, - /// followed by [scrollBehavior], and then the inherited ancestor - /// [ScrollBehavior]. + /// {@macro flutter.widgets.scrollable.scrollBehavior} /// /// The [ScrollBehavior] of the inherited [ScrollConfiguration] will be /// modified by default to not apply a [Scrollbar]. diff --git a/packages/flutter/lib/src/widgets/reorderable_list.dart b/packages/flutter/lib/src/widgets/reorderable_list.dart index 1900b3ad573..570735302ac 100644 --- a/packages/flutter/lib/src/widgets/reorderable_list.dart +++ b/packages/flutter/lib/src/widgets/reorderable_list.dart @@ -12,6 +12,7 @@ import 'package:flutter/scheduler.dart'; import 'basic.dart'; import 'debug.dart'; +import 'drag_boundary.dart'; import 'framework.dart'; import 'inherited_theme.dart'; import 'localizations.dart'; @@ -83,6 +84,37 @@ typedef ReorderCallback = void Function(int oldIndex, int newIndex); /// The returned value will typically be the [child] wrapped in other widgets. typedef ReorderItemProxyDecorator = Widget Function(Widget child, int index, Animation animation); +/// Used to provide drag boundaries during drag-and-drop reordering. +/// +/// {@tool snippet} +/// ```dart +/// DragBoundary( +/// child: CustomScrollView( +/// slivers: [ +/// SliverReorderableList( +/// itemBuilder: (BuildContext context, int index) { +/// return ReorderableDragStartListener( +/// key: ValueKey(index), +/// index: index, +/// child: Text('$index'), +/// ); +/// }, +/// dragBoundaryProvider: (BuildContext context) { +/// return DragBoundary.forRectOf(context); +/// }, +/// itemCount: 5, +/// onReorder: (int fromIndex, int toIndex) {}, +/// ), +/// ], +/// ) +/// ) +/// ``` +/// {@end-tool} +/// +/// See also: +/// * [DragBoundary], a widget that provides drag boundaries. +typedef ReorderDragBoundaryProvider = DragBoundaryDelegate? Function(BuildContext context); + /// A scrolling container that allows the user to interactively reorder the /// list items. /// @@ -139,6 +171,7 @@ class ReorderableList extends StatefulWidget { this.restorationId, this.clipBehavior = Clip.hardEdge, this.autoScrollerVelocityScalar, + this.dragBoundaryProvider, }) : assert(itemCount >= 0), assert( (itemExtent == null && prototypeItem == null) || @@ -271,6 +304,14 @@ class ReorderableList extends StatefulWidget { /// {@macro flutter.widgets.SliverReorderableList.autoScrollerVelocityScalar.default} final double? autoScrollerVelocityScalar; + /// {@template flutter.widgets.reorderable_list.dragBoundaryProvider} + /// A callback used to provide drag boundaries during drag-and-drop reordering. + /// + /// If null, the delegate returned by `DragBoundary.forRectMaybeOf` will be used. + /// Defaults to null. + /// {@endtemplate} + final ReorderDragBoundaryProvider? dragBoundaryProvider; + /// The state from the closest instance of this class that encloses the given /// context. /// @@ -388,6 +429,7 @@ class ReorderableListState extends State { _sliverReorderableListKey.currentState!.cancelReorder(); } + @protected @override Widget build(BuildContext context) { return CustomScrollView( @@ -418,6 +460,7 @@ class ReorderableListState extends State { onReorderEnd: widget.onReorderEnd, proxyDecorator: widget.proxyDecorator, autoScrollerVelocityScalar: widget.autoScrollerVelocityScalar, + dragBoundaryProvider: widget.dragBoundaryProvider, ), ), ], @@ -464,6 +507,7 @@ class SliverReorderableList extends StatefulWidget { this.itemExtentBuilder, this.prototypeItem, this.proxyDecorator, + this.dragBoundaryProvider, double? autoScrollerVelocityScalar, }) : autoScrollerVelocityScalar = autoScrollerVelocityScalar ?? _kDefaultAutoScrollVelocityScalar, assert(itemCount >= 0), @@ -514,6 +558,9 @@ class SliverReorderableList extends StatefulWidget { /// {@endtemplate} final double autoScrollerVelocityScalar; + /// {@macro flutter.widgets.reorderable_list.dragBoundaryProvider} + final ReorderDragBoundaryProvider? dragBoundaryProvider; + @override SliverReorderableListState createState() => SliverReorderableListState(); @@ -630,6 +677,7 @@ class SliverReorderableListState extends State with Ticke Axis get _scrollDirection => axisDirectionToAxis(_scrollable.axisDirection); bool get _reverse => axisDirectionIsReversed(_scrollable.axisDirection); + @protected @override void didChangeDependencies() { super.didChangeDependencies(); @@ -644,6 +692,7 @@ class SliverReorderableListState extends State with Ticke } } + @protected @override void didUpdateWidget(covariant SliverReorderableList oldWidget) { super.didUpdateWidget(oldWidget); @@ -661,6 +710,7 @@ class SliverReorderableListState extends State with Ticke } } + @protected @override void dispose() { _dragReset(); @@ -1030,6 +1080,7 @@ class SliverReorderableListState extends State with Ticke ); } + @protected @override Widget build(BuildContext context) { assert(debugCheckHasOverlay(context)); @@ -1343,9 +1394,15 @@ class _DragInfo extends Drag { index = item.index; child = item.widget.child; capturedThemes = item.widget.capturedThemes; - dragPosition = initialPosition; dragOffset = itemRenderBox.globalToLocal(initialPosition); itemSize = item.context.size!; + _rawDragPosition = initialPosition; + if (listState.widget.dragBoundaryProvider != null) { + boundary = listState.widget.dragBoundaryProvider!.call(listState.context); + } else { + boundary = DragBoundary.forRectMaybeOf(listState.context); + } + dragPosition = _adjustedDragOffset(initialPosition); itemExtent = _sizeExtent(itemSize, scrollDirection); itemLayoutConstraints = itemRenderBox.constraints; scrollable = Scrollable.of(item.context); @@ -1359,6 +1416,7 @@ class _DragInfo extends Drag { final ReorderItemProxyDecorator? proxyDecorator; final TickerProvider tickerProvider; + late DragBoundaryDelegate? boundary; late SliverReorderableListState listState; late int index; late Widget child; @@ -1370,6 +1428,7 @@ class _DragInfo extends Drag { late CapturedThemes capturedThemes; ScrollableState? scrollable; AnimationController? _proxyAnimation; + late Offset _rawDragPosition; void dispose() { if (kFlutterMemoryAllocationsEnabled) { @@ -1394,7 +1453,8 @@ class _DragInfo extends Drag { @override void update(DragUpdateDetails details) { final Offset delta = _restrictAxis(details.delta, scrollDirection); - dragPosition += delta; + _rawDragPosition += delta; + dragPosition = _adjustedDragOffset(_rawDragPosition); onUpdate?.call(this, dragPosition, details.delta); } @@ -1411,6 +1471,16 @@ class _DragInfo extends Drag { onCancel?.call(this); } + Offset _adjustedDragOffset(Offset offset) { + if (boundary == null) { + return offset; + } + final Offset adjOffset = boundary!.nearestPositionWithinBoundary( + (offset - dragOffset) & itemSize, + ).shift(dragOffset).topLeft; + return adjOffset; + } + void _dropCompleted() { _proxyAnimation?.dispose(); _proxyAnimation = null; diff --git a/packages/flutter/lib/src/widgets/routes.dart b/packages/flutter/lib/src/widgets/routes.dart index 5cce284980e..86764aa0ade 100644 --- a/packages/flutter/lib/src/widgets/routes.dart +++ b/packages/flutter/lib/src/widgets/routes.dart @@ -213,6 +213,23 @@ abstract class TransitionRoute extends OverlayRoute implements PredictiveB /// It defaults to `true`. bool willDisposeAnimationController = true; + /// Returns true if the transition has completed. + /// + /// It is equivalent to whether the future returned by [completed] has + /// completed. + /// + /// This method only works if assert is enabled. Otherwise it always returns + /// false. + @protected + bool debugTransitionCompleted() { + bool disposed = false; + assert(() { + disposed = _transitionCompleter.isCompleted; + return true; + }()); + return disposed; + } + /// Called to create the animation controller that will drive the transitions to /// this route from the previous one, and back to the previous route from this /// one. @@ -220,10 +237,9 @@ abstract class TransitionRoute extends OverlayRoute implements PredictiveB /// The returned controller will be disposed by [AnimationController.dispose] /// if the [willDisposeAnimationController] is `true`. AnimationController createAnimationController() { - assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.'); + assert(!debugTransitionCompleted(), 'Cannot reuse a $runtimeType after disposing it.'); final Duration duration = transitionDuration; final Duration reverseDuration = reverseTransitionDuration; - assert(duration >= Duration.zero); return AnimationController( duration: duration, reverseDuration: reverseDuration, @@ -236,11 +252,44 @@ abstract class TransitionRoute extends OverlayRoute implements PredictiveB /// the transition controlled by the animation controller created by /// [createAnimationController()]. Animation createAnimation() { - assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.'); + assert(!debugTransitionCompleted(), 'Cannot reuse a $runtimeType after disposing it.'); assert(_controller != null); return _controller!.view; } + Simulation? _simulation; + + /// Creates the simulation that drives the transition animation for this route. + /// + /// By default, this method returns null, indicating that the route doesn't + /// use simulations, but initiates the transition by calling either + /// [AnimationController.forward] or [AnimationController.reverse] with + /// [transitionDuration] and the controller's curve. + /// + /// Subclasses can override this method to return a non-null [Simulation]. In + /// this case, the [controller] will instead use the provided simulation to + /// animate the transition using [AnimationController.animateWith] or + /// [AnimationController.animateBackWith], and the [Simulation.x] is forwarded + /// to the value of [animation]. The [controller]'s curve and + /// [transitionDuration] are ignored. + /// + /// This method is invoked each time the navigator pushes or pops this route. + /// The `forward` parameter indicates the direction of the transition: true when + /// the route is pushed, and false when it is popped. + Simulation? createSimulation({ required bool forward }) { + assert(transitionDuration >= Duration.zero, + 'The `duration` must be positive for a non-simulation animation. Received $transitionDuration.'); + return null; + } + Simulation? _createSimulationAndVerify({ required bool forward }) { + final Simulation? simulation = createSimulation(forward: forward); + assert(transitionDuration >= Duration.zero, + "The `duration` must be positive for an animation that doesn't use simulation. " + 'Either set `transitionDuration` or set `createSimulation`. ' + 'Received $transitionDuration.'); + return simulation; + } + T? _result; void _handleStatusChanged(AnimationStatus status) { @@ -275,7 +324,7 @@ abstract class TransitionRoute extends OverlayRoute implements PredictiveB @override void install() { - assert(!_transitionCompleter.isCompleted, 'Cannot install a $runtimeType after disposing it.'); + assert(!debugTransitionCompleted(), 'Cannot install a $runtimeType after disposing it.'); _controller = createAnimationController(); assert(_controller != null, '$runtimeType.createAnimationController() returned null.'); _animation = createAnimation() @@ -290,15 +339,20 @@ abstract class TransitionRoute extends OverlayRoute implements PredictiveB @override TickerFuture didPush() { assert(_controller != null, '$runtimeType.didPush called before calling install() or after calling dispose().'); - assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.'); + assert(!debugTransitionCompleted(), 'Cannot reuse a $runtimeType after disposing it.'); super.didPush(); - return _controller!.forward(); + _simulation = _createSimulationAndVerify(forward: true); + if (_simulation == null) { + return _controller!.forward(); + } else { + return _controller!.animateWith(_simulation!); + } } @override void didAdd() { assert(_controller != null, '$runtimeType.didPush called before calling install() or after calling dispose().'); - assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.'); + assert(!debugTransitionCompleted(), 'Cannot reuse a $runtimeType after disposing it.'); super.didAdd(); _controller!.value = _controller!.upperBound; } @@ -306,7 +360,7 @@ abstract class TransitionRoute extends OverlayRoute implements PredictiveB @override void didReplace(Route? oldRoute) { assert(_controller != null, '$runtimeType.didReplace called before calling install() or after calling dispose().'); - assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.'); + assert(!debugTransitionCompleted(), 'Cannot reuse a $runtimeType after disposing it.'); if (oldRoute is TransitionRoute) { _controller!.value = oldRoute._controller!.value; } @@ -318,14 +372,19 @@ abstract class TransitionRoute extends OverlayRoute implements PredictiveB assert(_controller != null, '$runtimeType.didPop called before calling install() or after calling dispose().'); assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.'); _result = result; - _controller!.reverse(); + _simulation = _createSimulationAndVerify(forward: false); + if (_simulation == null) { + _controller!.reverse(); + } else { + _controller!.animateBackWith(_simulation!); + } return super.didPop(result); } @override void didPopNext(Route nextRoute) { assert(_controller != null, '$runtimeType.didPopNext called before calling install() or after calling dispose().'); - assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.'); + assert(!debugTransitionCompleted(), 'Cannot reuse a $runtimeType after disposing it.'); _updateSecondaryAnimation(nextRoute); super.didPopNext(nextRoute); } @@ -333,7 +392,7 @@ abstract class TransitionRoute extends OverlayRoute implements PredictiveB @override void didChangeNext(Route? nextRoute) { assert(_controller != null, '$runtimeType.didChangeNext called before calling install() or after calling dispose().'); - assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.'); + assert(!debugTransitionCompleted(), 'Cannot reuse a $runtimeType after disposing it.'); _updateSecondaryAnimation(nextRoute); super.didChangeNext(nextRoute); } @@ -562,6 +621,7 @@ abstract class TransitionRoute extends OverlayRoute implements PredictiveB @override void dispose() { assert(!_transitionCompleter.isCompleted, 'Cannot dispose a $runtimeType twice.'); + assert(!debugTransitionCompleted(), 'Cannot dispose a $runtimeType twice.'); _animation?.removeStatusListener(_handleStatusChanged); _performanceModeRequestHandle?.dispose(); _performanceModeRequestHandle = null; diff --git a/packages/flutter/lib/src/widgets/safe_area.dart b/packages/flutter/lib/src/widgets/safe_area.dart index 023e8fe1f1e..dcb1b036c94 100644 --- a/packages/flutter/lib/src/widgets/safe_area.dart +++ b/packages/flutter/lib/src/widgets/safe_area.dart @@ -16,19 +16,20 @@ import 'media_query.dart'; /// /// {@youtube 560 315 https://www.youtube.com/watch?v=lkF0TQJO0bA} /// -/// For example, this will indent the child by enough to avoid the status bar at -/// the top of the screen. -/// -/// It will also indent the child by the amount necessary to avoid The Notch on -/// the iPhone X, or other similar creative physical features of the display. -/// /// When a [minimum] padding is specified, the greater of the minimum padding /// or the safe area padding will be applied. /// +/// {@tool dartpad} +/// This example shows how `SafeArea` can apply padding within a mobile device's +/// screen to make the relevant content completely visible. +/// +/// ** See code in examples/api/lib/widgets/safe_area/safe_area.0.dart ** +/// {@end-tool} +/// /// {@tool snippet} /// /// This example creates a blue box containing text that is sufficiently padded -/// to avoid instrusions by the operating system. +/// to avoid intrusions by the operating system. /// /// ```dart /// SafeArea( diff --git a/packages/flutter/lib/src/widgets/scroll_notification_observer.dart b/packages/flutter/lib/src/widgets/scroll_notification_observer.dart index c143d0c1094..92248c82cd4 100644 --- a/packages/flutter/lib/src/widgets/scroll_notification_observer.dart +++ b/packages/flutter/lib/src/widgets/scroll_notification_observer.dart @@ -216,6 +216,7 @@ class ScrollNotificationObserverState extends State } } + @protected @override Widget build(BuildContext context) { return NotificationListener( @@ -239,6 +240,7 @@ class ScrollNotificationObserverState extends State ); } + @protected @override void dispose() { assert(_debugAssertNotDisposed()); diff --git a/packages/flutter/lib/src/widgets/scroll_view.dart b/packages/flutter/lib/src/widgets/scroll_view.dart index 087216670b2..629823536e5 100644 --- a/packages/flutter/lib/src/widgets/scroll_view.dart +++ b/packages/flutter/lib/src/widgets/scroll_view.dart @@ -256,12 +256,7 @@ abstract class ScrollView extends StatelessWidget { /// [physics]. final ScrollPhysics? physics; - /// {@macro flutter.widgets.shadow.scrollBehavior} - /// - /// [ScrollBehavior]s also provide [ScrollPhysics]. If an explicit - /// [ScrollPhysics] is provided in [physics], it will take precedence, - /// followed by [scrollBehavior], and then the inherited ancestor - /// [ScrollBehavior]. + /// {@macro flutter.widgets.scrollable.scrollBehavior} final ScrollBehavior? scrollBehavior; /// {@template flutter.widgets.scroll_view.shrinkWrap} diff --git a/packages/flutter/lib/src/widgets/scrollable.dart b/packages/flutter/lib/src/widgets/scrollable.dart index 57b55cb8fd7..22df141e9ca 100644 --- a/packages/flutter/lib/src/widgets/scrollable.dart +++ b/packages/flutter/lib/src/widgets/scrollable.dart @@ -304,12 +304,17 @@ class Scrollable extends StatefulWidget { /// {@endtemplate} final String? restorationId; - /// {@macro flutter.widgets.shadow.scrollBehavior} + /// {@template flutter.widgets.scrollable.scrollBehavior} + /// A [ScrollBehavior] that will be applied to this widget individually. + /// + /// Defaults to null, wherein the inherited [ScrollBehavior] is copied and + /// modified to alter the viewport decoration, like [Scrollbar]s. /// /// [ScrollBehavior]s also provide [ScrollPhysics]. If an explicit /// [ScrollPhysics] is provided in [physics], it will take precedence, /// followed by [scrollBehavior], and then the inherited ancestor /// [ScrollBehavior]. + /// {@endtemplate} final ScrollBehavior? scrollBehavior; /// {@macro flutter.material.Material.clipBehavior} @@ -606,12 +611,10 @@ class ScrollableState extends State with TickerProviderStateMixin, R // Only call this from places that will definitely trigger a rebuild. void _updatePosition() { _configuration = widget.scrollBehavior ?? ScrollConfiguration.of(context); - _physics = _configuration.getScrollPhysics(context); - if (widget.physics != null) { - _physics = widget.physics!.applyTo(_physics); - } else if (widget.scrollBehavior != null) { - _physics = widget.scrollBehavior!.getScrollPhysics(context).applyTo(_physics); - } + final ScrollPhysics? physicsFromWidget = widget.physics ?? widget.scrollBehavior?.getScrollPhysics(context); + _physics = _configuration.getScrollPhysics(context); + _physics = physicsFromWidget?.applyTo(_physics) ?? _physics; + final ScrollPosition? oldPosition = _position; if (oldPosition != null) { _effectiveScrollController.detach(oldPosition); @@ -626,6 +629,7 @@ class ScrollableState extends State with TickerProviderStateMixin, R _effectiveScrollController.attach(position); } + @protected @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(_persistedScrollOffset, 'offset'); @@ -635,6 +639,7 @@ class ScrollableState extends State with TickerProviderStateMixin, R } } + @protected @override void saveOffset(double offset) { assert(debugIsSerializableForRestoration(offset)); @@ -644,6 +649,7 @@ class ScrollableState extends State with TickerProviderStateMixin, R ServicesBinding.instance.restorationManager.flushData(); } + @protected @override void initState() { if (widget.controller == null) { @@ -652,6 +658,7 @@ class ScrollableState extends State with TickerProviderStateMixin, R super.initState(); } + @protected @override void didChangeDependencies() { _mediaQueryGestureSettings = MediaQuery.maybeGestureSettingsOf(context); @@ -680,6 +687,7 @@ class ScrollableState extends State with TickerProviderStateMixin, R return widget.controller?.runtimeType != oldWidget.controller?.runtimeType; } + @protected @override void didUpdateWidget(Scrollable oldWidget) { super.didUpdateWidget(oldWidget); @@ -711,6 +719,7 @@ class ScrollableState extends State with TickerProviderStateMixin, R } } + @protected @override void dispose() { if (widget.controller != null) { @@ -980,6 +989,7 @@ class ScrollableState extends State with TickerProviderStateMixin, R // DESCRIPTION + @protected @override Widget build(BuildContext context) { assert(_position != null); @@ -1020,6 +1030,7 @@ class ScrollableState extends State with TickerProviderStateMixin, R key: _scrollSemanticsKey, position: position, allowImplicitScrolling: _physics!.allowImplicitScrolling, + axis: widget.axis, semanticChildCount: widget.semanticChildCount, child: result, ) @@ -1064,6 +1075,7 @@ class ScrollableState extends State with TickerProviderStateMixin, R return (>[ ensureVisibleFuture ], this); } + @protected @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); @@ -1543,6 +1555,7 @@ class _ScrollSemantics extends SingleChildRenderObjectWidget { super.key, required this.position, required this.allowImplicitScrolling, + required this.axis, required this.semanticChildCount, super.child, }) : assert(semanticChildCount == null || semanticChildCount >= 0); @@ -1550,6 +1563,7 @@ class _ScrollSemantics extends SingleChildRenderObjectWidget { final ScrollPosition position; final bool allowImplicitScrolling; final int? semanticChildCount; + final Axis axis; @override _RenderScrollSemantics createRenderObject(BuildContext context) { @@ -1557,6 +1571,7 @@ class _ScrollSemantics extends SingleChildRenderObjectWidget { position: position, allowImplicitScrolling: allowImplicitScrolling, semanticChildCount: semanticChildCount, + axis: axis, ); } @@ -1564,6 +1579,7 @@ class _ScrollSemantics extends SingleChildRenderObjectWidget { void updateRenderObject(BuildContext context, _RenderScrollSemantics renderObject) { renderObject ..allowImplicitScrolling = allowImplicitScrolling + ..axis = axis ..position = position ..semanticChildCount = semanticChildCount; } @@ -1573,6 +1589,7 @@ class _RenderScrollSemantics extends RenderProxyBox { _RenderScrollSemantics({ required ScrollPosition position, required bool allowImplicitScrolling, + required this.axis, required int? semanticChildCount, RenderBox? child, }) : _position = position, @@ -1606,6 +1623,8 @@ class _RenderScrollSemantics extends RenderProxyBox { markNeedsSemanticsUpdate(); } + Axis axis; + int? get semanticChildCount => _semanticChildCount; int? _semanticChildCount; set semanticChildCount(int? value) { @@ -1616,6 +1635,14 @@ class _RenderScrollSemantics extends RenderProxyBox { markNeedsSemanticsUpdate(); } + void _onScrollToOffset(Offset targetOffset) { + final double offset = switch (axis) { + Axis.horizontal => targetOffset.dx, + Axis.vertical => targetOffset.dy, + }; + _position.jumpTo(offset); + } + @override void describeSemanticsConfiguration(SemanticsConfiguration config) { super.describeSemanticsConfiguration(config); @@ -1627,6 +1654,9 @@ class _RenderScrollSemantics extends RenderProxyBox { ..scrollExtentMax = _position.maxScrollExtent ..scrollExtentMin = _position.minScrollExtent ..scrollChildCount = semanticChildCount; + if (position.maxScrollExtent > position.minScrollExtent && allowImplicitScrolling) { + config.onScrollToOffset = _onScrollToOffset; + } } } @@ -1934,6 +1964,7 @@ class TwoDimensionalScrollableState extends State { return _horizontalInnerScrollableKey.currentState!; } + @protected @override void initState() { if (widget.verticalDetails.controller == null) { @@ -1945,6 +1976,7 @@ class TwoDimensionalScrollableState extends State { super.initState(); } + @protected @override void didUpdateWidget(TwoDimensionalScrollable oldWidget) { super.didUpdateWidget(oldWidget); @@ -1985,6 +2017,7 @@ class TwoDimensionalScrollableState extends State { } } + @protected @override Widget build(BuildContext context) { assert( @@ -2049,6 +2082,7 @@ class TwoDimensionalScrollableState extends State { ); } + @protected @override void dispose() { _verticalFallbackController?.dispose(); diff --git a/packages/flutter/lib/src/widgets/scrollable_helpers.dart b/packages/flutter/lib/src/widgets/scrollable_helpers.dart index 287536fe401..56cb64d55e7 100644 --- a/packages/flutter/lib/src/widgets/scrollable_helpers.dart +++ b/packages/flutter/lib/src/widgets/scrollable_helpers.dart @@ -460,17 +460,18 @@ class ScrollAction extends ContextAction { return true; }()); - if (primaryScrollController.position.context.notificationContext == null - && Scrollable.maybeOf(primaryScrollController.position.context.notificationContext!) == null) { + final BuildContext? notificationContext = primaryScrollController.position.context.notificationContext; + if (notificationContext != null) { + state = Scrollable.maybeOf(notificationContext); + } + if (state == null) { return; } - state = Scrollable.maybeOf(primaryScrollController.position.context.notificationContext!); } - assert(state != null, '$ScrollAction was invoked on a context that has no scrollable parent'); - assert(state!.position.hasPixels, 'Scrollable must be laid out before it can be scrolled via a ScrollAction'); + assert(state.position.hasPixels, 'Scrollable must be laid out before it can be scrolled via a ScrollAction'); // Don't do anything if the user isn't allowed to scroll. - if (state!.resolvedPhysics != null && !state.resolvedPhysics!.shouldAcceptUserOffset(state.position)) { + if (state.resolvedPhysics != null && !state.resolvedPhysics!.shouldAcceptUserOffset(state.position)) { return; } final double increment = getDirectionalIncrement(state, intent); diff --git a/packages/flutter/lib/src/widgets/scrollbar.dart b/packages/flutter/lib/src/widgets/scrollbar.dart index 9925d47f6e8..1d1aa0869ed 100644 --- a/packages/flutter/lib/src/widgets/scrollbar.dart +++ b/packages/flutter/lib/src/widgets/scrollbar.dart @@ -1378,6 +1378,7 @@ class RawScrollbarState extends State with TickerProv @protected bool get enableGestures => widget.interactive ?? true; + @protected @override void initState() { super.initState(); @@ -1404,6 +1405,7 @@ class RawScrollbarState extends State with TickerProv ); } + @protected @override void didChangeDependencies() { super.didChangeDependencies(); @@ -1562,6 +1564,7 @@ class RawScrollbarState extends State with TickerProv ..ignorePointer = !enableGestures; } + @protected @override void didUpdateWidget(T oldWidget) { super.didUpdateWidget(oldWidget); @@ -2159,6 +2162,7 @@ class RawScrollbarState extends State with TickerProv } } + @protected @override void dispose() { _fadeoutAnimationController.dispose(); @@ -2168,6 +2172,7 @@ class RawScrollbarState extends State with TickerProv super.dispose(); } + @protected @override Widget build(BuildContext context) { updateScrollbarPainter(); diff --git a/packages/flutter/lib/src/widgets/selectable_region.dart b/packages/flutter/lib/src/widgets/selectable_region.dart index 002237cdc59..a6bac976d5a 100644 --- a/packages/flutter/lib/src/widgets/selectable_region.dart +++ b/packages/flutter/lib/src/widgets/selectable_region.dart @@ -37,7 +37,6 @@ import 'text_selection.dart'; import 'text_selection_toolbar_anchors.dart'; // Examples can assume: -// FocusNode _focusNode = FocusNode(); // late GlobalKey key; const Set _kLongPressSelectionDevices = { @@ -105,7 +104,6 @@ const double _kSelectableVerticalComparingThreshold = 3.0; /// MaterialApp( /// home: SelectableRegion( /// selectionControls: materialTextSelectionControls, -/// focusNode: _focusNode, // initialized to FocusNode() /// child: Scaffold( /// appBar: AppBar(title: const Text('Flutter Code Sample')), /// body: ListView( @@ -188,6 +186,28 @@ const double _kSelectableVerticalComparingThreshold = 3.0; /// child selection area can not extend past its subtree, and the selection of /// the parent selection area can not extend inside the child selection area. /// +/// ## Selection status +/// +/// A [SelectableRegion]s [SelectableRegionSelectionStatus] is used to indicate whether +/// the [SelectableRegion] is actively changing the selection, or has finalized it. For +/// example, during a mouse click + drag, the [SelectableRegionSelectionStatus] will be +/// set to [SelectableRegionSelectionStatus.changing], and when the mouse click is released +/// the status will be set to [SelectableRegionSelectionStatus.finalized]. +/// +/// The default value of [SelectableRegion]s selection status +/// is [SelectableRegionSelectionStatus.finalized]. +/// +/// To access the [SelectableRegionSelectionStatus] of a parent [SelectableRegion] +/// use [SelectableRegionSelectionStatusScope.maybeOf] and retrieve the value from +/// the [ValueListenable]. +/// +/// One can also listen for changes to the [SelectableRegionSelectionStatus] by +/// adding a listener to the [ValueListenable] retrieved from [SelectableRegionSelectionStatusScope.maybeOf] +/// through [ValueListenable.addListener]. In Stateful widgets this is typically +/// done in [State.didChangeDependencies]. Remove the listener when no longer +/// needed, typically in your Stateful widgets [State.dispose] method through +/// [ValueListenable.removeListener]. +/// /// ## Tests /// /// In a test, a region can be selected either by faking drag events (e.g. using @@ -210,6 +230,8 @@ const double _kSelectableVerticalComparingThreshold = 3.0; /// selection events. /// * [SelectionContainer], which collects selectable widgets in the subtree /// and provides api to dispatch selection event to the collected widget. +/// * [SelectionListener], which enables accessing the [SelectionDetails] of +/// the selectable subtree it wraps. class SelectableRegion extends StatefulWidget { /// Create a new [SelectableRegion] widget. /// @@ -218,11 +240,11 @@ class SelectableRegion extends StatefulWidget { const SelectableRegion({ super.key, this.contextMenuBuilder, - required this.focusNode, - required this.selectionControls, - required this.child, + this.focusNode, this.magnifierConfiguration = TextMagnifierConfiguration.disabled, this.onSelectionChanged, + required this.selectionControls, + required this.child, }); /// The configuration for the magnifier used with selections in this region. @@ -235,7 +257,7 @@ class SelectableRegion extends StatefulWidget { final TextMagnifierConfiguration magnifierConfiguration; /// {@macro flutter.widgets.Focus.focusNode} - final FocusNode focusNode; + final FocusNode? focusNode; /// The child widget this selection area applies to. /// @@ -373,10 +395,18 @@ class SelectableRegionState extends State with TextSelectionDe /// The list of native text processing actions provided by the engine. final List _processTextActions = []; + // The focus node to use if the widget didn't supply one. + FocusNode? _localFocusNode; + FocusNode get _focusNode => widget.focusNode ?? (_localFocusNode ??= FocusNode(debugLabel: 'SelectableRegion')); + + /// Notifies its listeners when the selection state in this [SelectableRegion] changes. + final _SelectableRegionSelectionStatusNotifier _selectionStatusNotifier = _SelectableRegionSelectionStatusNotifier._(); + + @protected @override void initState() { super.initState(); - widget.focusNode.addListener(_handleFocusChanged); + _focusNode.addListener(_handleFocusChanged); _initMouseGestureRecognizer(); _initTouchGestureRecognizer(); // Right clicks. @@ -396,6 +426,7 @@ class SelectableRegionState extends State with TextSelectionDe _processTextActions.addAll(await _processTextService.queryTextActions()); } + @protected @override void didChangeDependencies() { super.didChangeDependencies(); @@ -422,13 +453,20 @@ class SelectableRegionState extends State with TextSelectionDe } } + @protected @override void didUpdateWidget(SelectableRegion oldWidget) { super.didUpdateWidget(oldWidget); if (widget.focusNode != oldWidget.focusNode) { - oldWidget.focusNode.removeListener(_handleFocusChanged); - widget.focusNode.addListener(_handleFocusChanged); - if (widget.focusNode.hasFocus != oldWidget.focusNode.hasFocus) { + if (oldWidget.focusNode == null && widget.focusNode != null) { + _localFocusNode?.removeListener(_handleFocusChanged); + _localFocusNode?.dispose(); + _localFocusNode = null; + } else if (widget.focusNode == null && oldWidget.focusNode != null) { + oldWidget.focusNode!.removeListener(_handleFocusChanged); + } + _focusNode.addListener(_handleFocusChanged); + if (_focusNode.hasFocus != oldWidget.focusNode?.hasFocus) { _handleFocusChanged(); } } @@ -439,7 +477,7 @@ class SelectableRegionState extends State with TextSelectionDe } void _handleFocusChanged() { - if (!widget.focusNode.hasFocus) { + if (!_focusNode.hasFocus) { if (kIsWeb) { PlatformSelectableRegionContextMenu.detach(_selectionDelegate); } @@ -452,6 +490,8 @@ class SelectableRegionState extends State with TextSelectionDe // case we want to retain the selection so it remains when we return to // the Flutter application. clearSelection(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; + _finalizeSelectableRegionStatus(); } } if (kIsWeb) { @@ -501,6 +541,14 @@ class SelectableRegionState extends State with TextSelectionDe } } + void _finalizeSelectableRegionStatus() { + if (_selectionStatusNotifier.value != SelectableRegionSelectionStatus.changing) { + // Don't finalize the selection again if it is not currently changing. + return; + } + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.finalized; + } + // Converts the details.consecutiveTapCount from a TapAndDrag*Details object, // which can grow to be infinitely large, to a value between 1 and the supported // max consecutive tap count. The value that the raw count is converted to is @@ -628,7 +676,7 @@ class SelectableRegionState extends State with TextSelectionDe _lastPointerDeviceKind = details.kind; switch (_getEffectiveConsecutiveTapCount(details.consecutiveTapCount)) { case 1: - widget.focusNode.requestFocus(); + _focusNode.requestFocus(); switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.fuchsia: @@ -647,9 +695,12 @@ class SelectableRegionState extends State with TextSelectionDe final bool isShiftPressedValid = _isShiftPressed && _selectionDelegate.value.startSelectionPoint != null; if (isShiftPressedValid) { _selectEndTo(offset: details.globalPosition); - return; + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; + break; } + clearSelection(); _collapseSelectionAt(offset: details.globalPosition); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; } case 2: switch (defaultTargetPlatform) { @@ -660,6 +711,7 @@ class SelectableRegionState extends State with TextSelectionDe break; } _selectWordAt(offset: details.globalPosition); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; if (details.kind != null && !_isPrecisePointerDevice(details.kind!)) { _showHandles(); } @@ -669,6 +721,7 @@ class SelectableRegionState extends State with TextSelectionDe case TargetPlatform.linux: case TargetPlatform.windows: _selectWordAt(offset: details.globalPosition); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; } case 3: switch (defaultTargetPlatform) { @@ -679,11 +732,13 @@ class SelectableRegionState extends State with TextSelectionDe // Triple tap on static text is only supported on mobile // platforms using a precise pointer device. _selectParagraphAt(offset: details.globalPosition); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; } case TargetPlatform.macOS: case TargetPlatform.linux: case TargetPlatform.windows: _selectParagraphAt(offset: details.globalPosition); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; } } _updateSelectedContentIfNeeded(); @@ -697,6 +752,7 @@ class SelectableRegionState extends State with TextSelectionDe return; } _selectStartTo(offset: details.globalPosition); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; } _updateSelectedContentIfNeeded(); } @@ -709,6 +765,7 @@ class SelectableRegionState extends State with TextSelectionDe return; } _selectEndTo(offset: details.globalPosition, continuous: true); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; case 2: switch (defaultTargetPlatform) { case TargetPlatform.android: @@ -717,6 +774,7 @@ class SelectableRegionState extends State with TextSelectionDe // pointer device or when not on the web. if (!kIsWeb || details.kind != null && _isPrecisePointerDevice(details.kind!)) { _selectEndTo(offset: details.globalPosition, continuous: true, textGranularity: TextGranularity.word); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; } case TargetPlatform.iOS: if (kIsWeb && details.kind != null && !_isPrecisePointerDevice(details.kind!) && _doubleTapOffset != null) { @@ -726,6 +784,7 @@ class SelectableRegionState extends State with TextSelectionDe _doubleTapOffset = null; } _selectEndTo(offset: details.globalPosition, continuous: true, textGranularity: TextGranularity.word); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; if (details.kind != null && !_isPrecisePointerDevice(details.kind!)) { _showHandles(); } @@ -733,6 +792,7 @@ class SelectableRegionState extends State with TextSelectionDe case TargetPlatform.linux: case TargetPlatform.windows: _selectEndTo(offset: details.globalPosition, continuous: true, textGranularity: TextGranularity.word); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; } case 3: switch (defaultTargetPlatform) { @@ -743,31 +803,35 @@ class SelectableRegionState extends State with TextSelectionDe // a precise pointer device. if (details.kind != null && _isPrecisePointerDevice(details.kind!)) { _selectEndTo(offset: details.globalPosition, continuous: true, textGranularity: TextGranularity.paragraph); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; } case TargetPlatform.macOS: case TargetPlatform.linux: case TargetPlatform.windows: _selectEndTo(offset: details.globalPosition, continuous: true, textGranularity: TextGranularity.paragraph); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; } } _updateSelectedContentIfNeeded(); } void _handleMouseDragEnd(TapDragEndDetails details) { - final bool isPointerPrecise = _lastPointerDeviceKind != null && _lastPointerDeviceKind == PointerDeviceKind.mouse; + assert(_lastPointerDeviceKind != null); + final bool isPointerPrecise = _isPrecisePointerDevice(_lastPointerDeviceKind!); + // On mobile platforms like android, fuchsia, and iOS, a drag gesture will + // only show the selection overlay when the drag has finished and the pointer + // device kind is not precise, for example at the end of a double tap + drag + // to select on native iOS. + final bool shouldShowSelectionOverlayOnMobile = !isPointerPrecise; switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.fuchsia: - if (!isPointerPrecise) { - // On Android, a drag gesture will only show the selection overlay when - // the drag has finished and the pointer device kind is not precise. + if (shouldShowSelectionOverlayOnMobile) { _showHandles(); _showToolbar(); } case TargetPlatform.iOS: - if (!isPointerPrecise) { - // On iOS, a drag gesture will only show the selection toolbar when - // the drag has finished and the pointer device kind is not precise. + if (shouldShowSelectionOverlayOnMobile) { _showToolbar(); } case TargetPlatform.macOS: @@ -778,6 +842,7 @@ class SelectableRegionState extends State with TextSelectionDe } _finalizeSelection(); _updateSelectedContentIfNeeded(); + _finalizeSelectableRegionStatus(); } void _handleMouseTapUp(TapDragUpDetails details) { @@ -800,11 +865,11 @@ class SelectableRegionState extends State with TextSelectionDe case TargetPlatform.iOS: hideToolbar(); _collapseSelectionAt(offset: details.globalPosition); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; case TargetPlatform.macOS: case TargetPlatform.linux: case TargetPlatform.windows: // On desktop platforms the selection is set on tap down. - break; } case 2: final bool isPointerPrecise = _isPrecisePointerDevice(details.kind); @@ -819,6 +884,10 @@ class SelectableRegionState extends State with TextSelectionDe } case TargetPlatform.iOS: if (!isPointerPrecise) { + if (kIsWeb) { + // Double tap on iOS web only triggers when a drag begins after the double tap. + break; + } // On iOS, a double tap will only show the selection toolbar after // the following tap up when the pointer device kind is not precise. _showToolbar(); @@ -831,20 +900,26 @@ class SelectableRegionState extends State with TextSelectionDe break; } } + _finalizeSelectableRegionStatus(); _updateSelectedContentIfNeeded(); } void _updateSelectedContentIfNeeded() { - if (_lastSelectedContent?.plainText != _selectable?.getSelectedContent()?.plainText) { - _lastSelectedContent = _selectable?.getSelectedContent(); - widget.onSelectionChanged?.call(_lastSelectedContent); + if (widget.onSelectionChanged == null) { + return; + } + final SelectedContent? content = _selectable?.getSelectedContent(); + if (_lastSelectedContent?.plainText != content?.plainText) { + _lastSelectedContent = content; + widget.onSelectionChanged!.call(_lastSelectedContent); } } void _handleTouchLongPressStart(LongPressStartDetails details) { HapticFeedback.selectionClick(); - widget.focusNode.requestFocus(); + _focusNode.requestFocus(); _selectWordAt(offset: details.globalPosition); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; // Platforms besides Android will show the text selection handles when // the long press is initiated. Android shows the text selection handles when // the long press has ended, usually after a pointer up event is received. @@ -856,12 +931,14 @@ class SelectableRegionState extends State with TextSelectionDe void _handleTouchLongPressMoveUpdate(LongPressMoveUpdateDetails details) { _selectEndTo(offset: details.globalPosition, textGranularity: TextGranularity.word); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; _updateSelectedContentIfNeeded(); } void _handleTouchLongPressEnd(LongPressEndDetails details) { _finalizeSelection(); _updateSelectedContentIfNeeded(); + _finalizeSelectableRegionStatus(); _showToolbar(); if (defaultTargetPlatform == TargetPlatform.android) { _showHandles(); @@ -883,7 +960,7 @@ class SelectableRegionState extends State with TextSelectionDe final Offset? previousSecondaryTapDownPosition = _lastSecondaryTapDownPosition; final bool toolbarIsVisible = _selectionOverlay?.toolbarIsVisible ?? false; _lastSecondaryTapDownPosition = details.globalPosition; - widget.focusNode.requestFocus(); + _focusNode.requestFocus(); switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.fuchsia: @@ -891,23 +968,24 @@ class SelectableRegionState extends State with TextSelectionDe // If _lastSecondaryTapDownPosition is within the current selection then // keep the current selection, if not then collapse it. final bool lastSecondaryTapDownPositionWasOnActiveSelection = _positionIsOnActiveSelection(globalPosition: details.globalPosition); - if (!lastSecondaryTapDownPositionWasOnActiveSelection) { - _collapseSelectionAt(offset: _lastSecondaryTapDownPosition!); + if (lastSecondaryTapDownPositionWasOnActiveSelection) { + // Restore _lastSecondaryTapDownPosition since it may be cleared if a user + // accesses contextMenuAnchors. + _lastSecondaryTapDownPosition = details.globalPosition; + _showHandles(); + _showToolbar(location: _lastSecondaryTapDownPosition); + _updateSelectedContentIfNeeded(); + return; } - _showHandles(); - _showToolbar(location: _lastSecondaryTapDownPosition); + _collapseSelectionAt(offset: _lastSecondaryTapDownPosition!); case TargetPlatform.iOS: _selectWordAt(offset: _lastSecondaryTapDownPosition!); - _showHandles(); - _showToolbar(location: _lastSecondaryTapDownPosition); case TargetPlatform.macOS: if (previousSecondaryTapDownPosition == _lastSecondaryTapDownPosition && toolbarIsVisible) { hideToolbar(); return; } _selectWordAt(offset: _lastSecondaryTapDownPosition!); - _showHandles(); - _showToolbar(location: _lastSecondaryTapDownPosition); case TargetPlatform.linux: if (toolbarIsVisible) { hideToolbar(); @@ -919,9 +997,14 @@ class SelectableRegionState extends State with TextSelectionDe if (!lastSecondaryTapDownPositionWasOnActiveSelection) { _collapseSelectionAt(offset: _lastSecondaryTapDownPosition!); } - _showHandles(); - _showToolbar(location: _lastSecondaryTapDownPosition); } + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; + _finalizeSelectableRegionStatus(); + // Restore _lastSecondaryTapDownPosition since it may be cleared if a user + // accesses contextMenuAnchors. + _lastSecondaryTapDownPosition = details.globalPosition; + _showHandles(); + _showToolbar(location: _lastSecondaryTapDownPosition); _updateSelectedContentIfNeeded(); } @@ -971,9 +1054,9 @@ class SelectableRegionState extends State with TextSelectionDe }, ); } - _stopSelectionStartEdgeUpdate(); - _stopSelectionEndEdgeUpdate(); + _finalizeSelection(); _updateSelectedContentIfNeeded(); + _finalizeSelectableRegionStatus(); } void _stopSelectionEndEdgeUpdate() { @@ -1048,6 +1131,7 @@ class SelectableRegionState extends State with TextSelectionDe _selectionDelegate.value.startSelectionPoint!, )); _updateSelectedContentIfNeeded(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; } void _handleSelectionEndHandleDragStart(DragStartDetails details) { @@ -1075,6 +1159,7 @@ class SelectableRegionState extends State with TextSelectionDe _selectionDelegate.value.endSelectionPoint!, )); _updateSelectedContentIfNeeded(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; } MagnifierInfo _buildInfoForMagnifier(Offset globalGesturePosition, SelectionPoint selectionPoint) { @@ -1106,12 +1191,12 @@ class SelectableRegionState extends State with TextSelectionDe _selectionOverlay = SelectionOverlay( context: context, debugRequiredFor: widget, - startHandleType: start?.handleType ?? TextSelectionHandleType.left, + startHandleType: start?.handleType ?? TextSelectionHandleType.collapsed, lineHeightAtStart: start?.lineHeight ?? end!.lineHeight, onStartHandleDragStart: _handleSelectionStartHandleDragStart, onStartHandleDragUpdate: _handleSelectionStartHandleDragUpdate, onStartHandleDragEnd: _onAnyDragEnd, - endHandleType: end?.handleType ?? TextSelectionHandleType.right, + endHandleType: end?.handleType ?? TextSelectionHandleType.collapsed, lineHeightAtEnd: end?.lineHeight ?? start!.lineHeight, onEndHandleDragStart: _handleSelectionEndHandleDragStart, onEndHandleDragUpdate: _handleSelectionEndHandleDragUpdate, @@ -1299,6 +1384,8 @@ class SelectableRegionState extends State with TextSelectionDe /// * [_selectParagraphAt], which selects an entire paragraph at the location. /// * [selectAll], which selects the entire content. void _collapseSelectionAt({required Offset offset}) { + // There may be other selection ongoing. + _finalizeSelection(); _selectStartTo(offset: offset); _selectEndTo(offset: offset); } @@ -1399,9 +1486,13 @@ class SelectableRegionState extends State with TextSelectionDe /// for the default context menu buttons. TextSelectionToolbarAnchors get contextMenuAnchors { if (_lastSecondaryTapDownPosition != null) { - return TextSelectionToolbarAnchors( + final TextSelectionToolbarAnchors anchors = TextSelectionToolbarAnchors( primaryAnchor: _lastSecondaryTapDownPosition!, ); + // Clear the state of _lastSecondaryTapDownPosition after use since a user may + // access contextMenuAnchors and receive invalid anchors for their context menu. + _lastSecondaryTapDownPosition = null; + return anchors; } final RenderBox renderBox = context.findRenderObject()! as RenderBox; return TextSelectionToolbarAnchors.fromSelection( @@ -1445,6 +1536,8 @@ class SelectableRegionState extends State with TextSelectionDe ), ); _updateSelectedContentIfNeeded(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; + _finalizeSelectableRegionStatus(); } double? _directionalHorizontalBaseline; @@ -1467,6 +1560,8 @@ class SelectableRegionState extends State with TextSelectionDe ), ); _updateSelectedContentIfNeeded(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; + _finalizeSelectableRegionStatus(); } // [TextSelectionDelegate] overrides. @@ -1498,6 +1593,8 @@ class SelectableRegionState extends State with TextSelectionDe case TargetPlatform.android: case TargetPlatform.fuchsia: clearSelection(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; + _finalizeSelectableRegionStatus(); case TargetPlatform.iOS: hideToolbar(false); case TargetPlatform.linux: @@ -1527,6 +1624,8 @@ class SelectableRegionState extends State with TextSelectionDe case TargetPlatform.android: case TargetPlatform.fuchsia: clearSelection(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; + _finalizeSelectableRegionStatus(); case TargetPlatform.iOS: hideToolbar(false); case TargetPlatform.linux: @@ -1627,6 +1726,8 @@ class SelectableRegionState extends State with TextSelectionDe _showHandles(); } _updateSelectedContentIfNeeded(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; + _finalizeSelectableRegionStatus(); } @Deprecated( @@ -1637,6 +1738,8 @@ class SelectableRegionState extends State with TextSelectionDe void copySelection(SelectionChangedCause cause) { _copy(); clearSelection(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; + _finalizeSelectableRegionStatus(); } @Deprecated( @@ -1696,26 +1799,35 @@ class SelectableRegionState extends State with TextSelectionDe _selectable = null; } + @protected @override void dispose() { _selectable?.removeListener(_updateSelectionStatus); _selectable?.pushHandleLayers(null, null); _selectionDelegate.dispose(); + _selectionStatusNotifier.dispose(); // In case dispose was triggered before gesture end, remove the magnifier // so it doesn't remain stuck in the overlay forever. _selectionOverlay?.hideMagnifier(); _selectionOverlay?.dispose(); _selectionOverlay = null; + widget.focusNode?.removeListener(_handleFocusChanged); + _localFocusNode?.removeListener(_handleFocusChanged); + _localFocusNode?.dispose(); super.dispose(); } + @protected @override Widget build(BuildContext context) { assert(debugCheckHasOverlay(context)); - Widget result = SelectionContainer( - registrar: this, - delegate: _selectionDelegate, - child: widget.child, + Widget result = SelectableRegionSelectionStatusScope._( + selectionStatusNotifier: _selectionStatusNotifier, + child: SelectionContainer( + registrar: this, + delegate: _selectionDelegate, + child: widget.child, + ), ); if (kIsWeb) { result = PlatformSelectableRegionContextMenu( @@ -1730,9 +1842,9 @@ class SelectableRegionState extends State with TextSelectionDe excludeFromSemantics: true, child: Actions( actions: _actions, - child: Focus( + child: Focus.withExternalFocusNode( includeSemantics: false, - focusNode: widget.focusNode, + focusNode: _focusNode, child: result, ), ), @@ -2561,6 +2673,76 @@ abstract class MultiSelectableSelectionContainerDelegate extends SelectionContai ); } + /// The total length of the content under this [SelectionContainerDelegate]. + /// + /// This value is derived from the [Selectable.contentLength] of each [Selectable] + /// managed by this delegate. + @override + int get contentLength => selectables.fold(0, (int sum, Selectable selectable) => sum + selectable.contentLength); + + /// This method calculates a local [SelectedContentRange] based on the list + /// of [selections] that are accumulated from the [Selectable] children under this + /// delegate. This calculation takes into account the accumulated content + /// length before the active selection, and returns null when either selection + /// edge has not been set. + SelectedContentRange? _calculateLocalRange(List<_SelectionInfo> selections) { + if (currentSelectionStartIndex == -1 || currentSelectionEndIndex == -1) { + return null; + } + int startOffset = 0; + int endOffset = 0; + bool foundStart = false; + bool forwardSelection = currentSelectionEndIndex >= currentSelectionStartIndex; + if (currentSelectionEndIndex == currentSelectionStartIndex) { + // Determining selection direction is innacurate if currentSelectionStartIndex == currentSelectionEndIndex. + // Use the range from the selectable within the selection as the source of truth for selection direction. + final SelectedContentRange rangeAtSelectableInSelection = selectables[currentSelectionStartIndex].getSelection()!; + forwardSelection = rangeAtSelectableInSelection.endOffset >= rangeAtSelectableInSelection.startOffset; + } + for (int index = 0; index < selections.length; index++) { + final _SelectionInfo selection = selections[index]; + if (selection.range == null) { + if (foundStart) { + return SelectedContentRange( + startOffset: forwardSelection ? startOffset : endOffset, + endOffset: forwardSelection ? endOffset : startOffset, + ); + } + startOffset += selection.contentLength; + endOffset = startOffset; + continue; + } + final int selectionStartNormalized = min(selection.range!.startOffset, selection.range!.endOffset); + final int selectionEndNormalized = max(selection.range!.startOffset, selection.range!.endOffset); + if (!foundStart) { + startOffset += selectionStartNormalized; + endOffset = startOffset + (selectionEndNormalized - selectionStartNormalized).abs(); + foundStart = true; + } else { + endOffset += (selectionEndNormalized - selectionStartNormalized).abs(); + } + } + assert(foundStart, 'The start of the selection has not been found despite this selection delegate having an existing currentSelectionStartIndex and currentSelectionEndIndex.'); + return SelectedContentRange( + startOffset: forwardSelection ? startOffset : endOffset, + endOffset: forwardSelection ? endOffset : startOffset, + ); + } + + /// Returns a [SelectedContentRange] considering the [SelectedContentRange] + /// from each [Selectable] child managed under this delegate. + /// + /// When nothing is selected or either selection edge has not been set, + /// this method will return `null`. + @override + SelectedContentRange? getSelection() { + final List<_SelectionInfo> selections = <_SelectionInfo>[ + for (final Selectable selectable in selectables) + (contentLength: selectable.contentLength, range: selectable.getSelection()), + ]; + return _calculateLocalRange(selections); + } + // Clears the selection on all selectables not in the range of // currentSelectionStartIndex..currentSelectionEndIndex. // @@ -2989,6 +3171,10 @@ abstract class MultiSelectableSelectionContainerDelegate extends SelectionContai } } +/// The length of the content that can be selected, and the range that is +/// selected. +typedef _SelectionInfo = ({int contentLength, SelectedContentRange? range}); + /// Signature for a widget builder that builds a context menu for the given /// [SelectableRegionState]. /// @@ -3000,3 +3186,280 @@ typedef SelectableRegionContextMenuBuilder = Widget Function( BuildContext context, SelectableRegionState selectableRegionState, ); + +/// The status of the selection under a [SelectableRegion]. +/// +/// This value can be accessed for a [SelectableRegion] by using +/// [SelectableRegionSelectionStatusScope.maybeOf]. +/// +/// This value under a [SelectableRegion] is updated frequently +/// during selection gestures such as clicks and taps to select +/// and keyboard shortcuts. +enum SelectableRegionSelectionStatus { + /// Indicates that the selection under a [SelectableRegion] is changing. + /// + /// A [SelectableRegion]s selection is changing when it is being + /// updated by user through selection gestures and keyboard shortcuts. + /// For example, during a text selection drag with a click + drag, + /// a [SelectableRegion]s selection is considered changing until + /// the user releases the click, then it will be considered finalized. + changing, + + /// Indicates that the selection under a [SelectableRegion] is finalized. + /// + /// A [SelectableRegion]s selection is finalized when it is no longer + /// being updated by the user through selection gestures or keyboard + /// shortcuts. For example, the selection will be finalized on a mouse + /// drag end, touch long press drag end, a single click to collapse the + /// selection, a double click/tap to select a word, ctrl + A / cmd + A to + /// select all, or a triple click/tap to select a paragraph. + finalized, +} + +/// Notifies its listeners when the [SelectableRegion] that created this object +/// is changing or finalizes its selection. +/// +/// To access the [_SelectableRegionSelectionStatusNotifier] from the nearest [SelectableRegion] +/// ancestor, use [SelectableRegionSelectionStatusScope.maybeOf]. +final class _SelectableRegionSelectionStatusNotifier extends ChangeNotifier implements ValueListenable { + _SelectableRegionSelectionStatusNotifier._(); + + SelectableRegionSelectionStatus _selectableRegionSelectionStatus = SelectableRegionSelectionStatus.finalized; + /// The current value of the [SelectableRegionSelectionStatus] of the [SelectableRegion] + /// that owns this object. + /// + /// Defaults to [SelectableRegionSelectionStatus.finalized]. + @override + SelectableRegionSelectionStatus get value => _selectableRegionSelectionStatus; + + /// Sets the [SelectableRegionSelectionStatus] for the [SelectableRegion] that + /// owns this object. + /// + /// Listeners are notified even if the value did not change. + @protected + set value(SelectableRegionSelectionStatus newStatus) { + assert(newStatus == SelectableRegionSelectionStatus.finalized && value == SelectableRegionSelectionStatus.changing + || newStatus == SelectableRegionSelectionStatus.changing, + 'Attempting to finalize the selection when it is already finalized.'); + _selectableRegionSelectionStatus = newStatus; + notifyListeners(); + } +} + +/// Notifies its listeners when the selection under a [SelectableRegion] or +/// [SelectionArea] is being changed or finalized. +/// +/// Use [SelectableRegionSelectionStatusScope.maybeOf], to access the [ValueListenable] of type +/// [SelectableRegionSelectionStatus] under a [SelectableRegion]. Its listeners +/// will be called even when the value of the [SelectableRegionSelectionStatus] +/// does not change. +final class SelectableRegionSelectionStatusScope extends InheritedWidget { + const SelectableRegionSelectionStatusScope._({ + required this.selectionStatusNotifier, + required super.child, + }); + + /// Tracks updates to the [SelectableRegionSelectionStatus] of the owning + /// [SelectableRegion]. + /// + /// Listeners will be called even when the value of the [SelectableRegionSelectionStatus] + /// does not change. The selection under the [SelectableRegion] still may have changed. + final ValueListenable selectionStatusNotifier; + + /// The closest instance of this class that encloses the given context. + /// + /// If there is no enclosing [SelectableRegion] or [SelectionArea] widget, then null is + /// returned. + /// + /// Calling this method will create a dependency on the closest + /// [SelectableRegionSelectionStatusScope] in the [context], if there is one. + static ValueListenable? maybeOf(BuildContext context) { + return context.dependOnInheritedWidgetOfExactType()?.selectionStatusNotifier; + } + + @override + bool updateShouldNotify(SelectableRegionSelectionStatusScope oldWidget) { + return selectionStatusNotifier != oldWidget.selectionStatusNotifier; + } +} + +/// A [SelectionContainer] that allows the user to access the [SelectionDetails] and +/// listen to selection changes for the child subtree it wraps under a [SelectionArea] +/// or [SelectableRegion]. +/// +/// The selection updates are provided through the [selectionNotifier], to listen +/// to these updates attach a listener through [SelectionListenerNotifier.addListener]. +/// +/// This widget does not listen to selection changes of nested [SelectionArea]s +/// or [SelectableRegion]s in its subtree because those widgets are self-contained +/// and do not bubble up their selection. To listen to selection changes of a +/// [SelectionArea] or [SelectableRegion] under this [SelectionListener], add +/// an additional [SelectionListener] under each one. +/// +/// {@tool dartpad} +/// This example shows how to use [SelectionListener] to access the [SelectionDetails] +/// under a [SelectionArea] or [SelectableRegion]. +/// +/// ** See code in examples/api/lib/material/selection_area/selection_area.1.dart ** +/// {@end-tool} +/// +/// {@tool dartpad} +/// This example shows how to color the active selection red under a +/// [SelectionArea] or [SelectableRegion]. +/// +/// ** See code in examples/api/lib/material/selection_area/selection_area.2.dart ** +/// {@end-tool} +/// +/// See also: +/// +/// * [SelectableRegion], which provides an overview of the selection system. +class SelectionListener extends StatefulWidget { + /// Create a new [SelectionListener] widget. + const SelectionListener({ + super.key, + required this.selectionNotifier, + required this.child, + }); + + /// Notifies listeners when the selection has changed. + final SelectionListenerNotifier selectionNotifier; + + /// The child widget this selection listener applies to. + /// + /// {@macro flutter.widgets.ProxyWidget.child} + final Widget child; + + @override + State createState() => _SelectionListenerState(); +} + +class _SelectionListenerState extends State { + late final _SelectionListenerDelegate _selectionDelegate = _SelectionListenerDelegate(selectionNotifier: widget.selectionNotifier); + + @override + void didUpdateWidget(SelectionListener oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.selectionNotifier != widget.selectionNotifier) { + _selectionDelegate._setNotifier(widget.selectionNotifier); + } + } + + @override + void dispose() { + _selectionDelegate.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return SelectionContainer( + delegate: _selectionDelegate, + child: widget.child, + ); + } +} + +final class _SelectionListenerDelegate extends StaticSelectionContainerDelegate implements SelectionDetails { + _SelectionListenerDelegate({ + required SelectionListenerNotifier selectionNotifier, + }) : _selectionNotifier = selectionNotifier { + _selectionNotifier._registerSelectionListenerDelegate(this); + } + + SelectionGeometry? _initialSelectionGeometry; + + SelectionListenerNotifier _selectionNotifier; + void _setNotifier(SelectionListenerNotifier newNotifier) { + _selectionNotifier._unregisterSelectionListenerDelegate(); + _selectionNotifier = newNotifier; + _selectionNotifier._registerSelectionListenerDelegate(this); + } + + @override + void notifyListeners() { + super.notifyListeners(); + // Skip initial notification if selection is not valid. + if (_initialSelectionGeometry == null && !value.hasSelection) { + _initialSelectionGeometry = value; + return; + } + _selectionNotifier.notifyListeners(); + } + + @override + void dispose() { + _selectionNotifier._unregisterSelectionListenerDelegate(); + _initialSelectionGeometry = null; + super.dispose(); + } + + @override + SelectedContentRange? get range => getSelection(); + + @override + SelectionStatus get status => value.status; +} + +/// A read-only interface for accessing the details of a selection under a [SelectionListener]. +/// +/// This includes information such as the status of the selection indicating +/// if it is collapsed or uncollapsed, the [SelectedContentRange] that includes +/// the start and end offsets of the selection local to the [SelectionListener] +/// that reports this object. +/// +/// This object is typically accessed by providing a [SelectionListenerNotifier] +/// to a [SelectionListener] and retrieving the value from [SelectionListenerNotifier.selection]. +abstract final class SelectionDetails { + /// The computed selection range of the owning [SelectionListener]s subtree. + /// + /// Returns `null` if there is nothing selected. + SelectedContentRange? get range; + + /// The status that indicates whether there is a selection and whether the selection is collapsed. + SelectionStatus get status; +} + +/// Notifies listeners when the selection under a [SelectionListener] has been +/// changed. +/// +/// This object is typically provided to a [SelectionListener]. +final class SelectionListenerNotifier extends ChangeNotifier { + _SelectionListenerDelegate? _selectionDelegate; + + /// The details of the selection under the [SelectionListener] that owns this notifier. + /// + /// Throws an exception if this notifier has not been registered to a [SelectionListener]. + /// To check if a notifier has been registered to a [SelectionListener] use [registered]. + SelectionDetails get selection => _selectionDelegate ?? (throw Exception('Selection client has not been registered to this notifier.')); + + /// Whether this [SelectionListenerNotifier] has been registered to a [SelectionListener]. + bool get registered => _selectionDelegate != null; + + void _registerSelectionListenerDelegate(_SelectionListenerDelegate selectionDelegate) { + assert( + !registered, + 'This SelectionListenerNotifier is already registered to another SelectionListener. Try providing a new SelectionListenerNotifier.', + ); + _selectionDelegate = selectionDelegate; + } + + void _unregisterSelectionListenerDelegate() { + _selectionDelegate = null; + } + + // From ChangeNotifier. + @override + void dispose() { + _unregisterSelectionListenerDelegate(); + super.dispose(); + } + + /// Calls the listener every time the [SelectionGeometry] of the selection changes under + /// a [SelectionListener]. + /// + /// Listeners can be removed with [removeListener]. + @override + void addListener(VoidCallback listener) { + super.addListener(listener); + } +} diff --git a/packages/flutter/lib/src/widgets/selection_container.dart b/packages/flutter/lib/src/widgets/selection_container.dart index bd5e86cde4a..a0cafe54766 100644 --- a/packages/flutter/lib/src/widgets/selection_container.dart +++ b/packages/flutter/lib/src/widgets/selection_container.dart @@ -182,6 +182,12 @@ class _SelectionContainerState extends State with Selectable return widget.delegate!.getSelectedContent(); } + @override + SelectedContentRange? getSelection() { + assert(!widget._disabled); + return widget.delegate!.getSelection(); + } + @override SelectionResult dispatchSelectionEvent(SelectionEvent event) { assert(!widget._disabled); @@ -202,6 +208,9 @@ class _SelectionContainerState extends State with Selectable return context.findRenderObject()!.getTransformTo(ancestor); } + @override + int get contentLength => widget.delegate!.contentLength; + @override Size get size => (context.findRenderObject()! as RenderBox).size; diff --git a/packages/flutter/lib/src/widgets/semantics_debugger.dart b/packages/flutter/lib/src/widgets/semantics_debugger.dart index 937e89d0014..97d73e39675 100644 --- a/packages/flutter/lib/src/widgets/semantics_debugger.dart +++ b/packages/flutter/lib/src/widgets/semantics_debugger.dart @@ -202,7 +202,7 @@ class _SemanticsDebuggerPainter extends CustomPainter { canvas.save(); canvas.scale(1.0 / devicePixelRatio, 1.0 / devicePixelRatio); if (rootNode != null) { - _paint(canvas, rootNode, _findDepth(rootNode)); + _paint(canvas, rootNode, _findDepth(rootNode), 0, 0); } if (pointerPosition != null) { final Paint paint = Paint(); @@ -332,14 +332,14 @@ class _SemanticsDebuggerPainter extends CustomPainter { return childrenDepth + 1; } - void _paint(Canvas canvas, SemanticsNode node, int rank) { + void _paint(Canvas canvas, SemanticsNode node, int rank, int indexInParent, int level) { canvas.save(); if (node.transform != null) { canvas.transform(node.transform!.storage); } final Rect rect = node.rect; if (!rect.isEmpty) { - final Color lineColor = Color(0xFF000000 + math.Random(node.id).nextInt(0xFFFFFF)); + final Color lineColor = _colorForNode(indexInParent, level); final Rect innerRect = rect.deflate(rank * 1.0); if (innerRect.isEmpty) { final Paint fill = Paint() @@ -361,13 +361,31 @@ class _SemanticsDebuggerPainter extends CustomPainter { } if (!node.mergeAllDescendantsIntoThisNode) { final int childRank = rank - 1; + final int childLevel = level + 1; + int childIndex = 0; node.visitChildren((SemanticsNode child) { - _paint(canvas, child, childRank); + _paint(canvas, child, childRank, childIndex, childLevel); + childIndex += 1; return true; }); } canvas.restore(); } + + static Color _colorForNode(int index, int level) { + return HSLColor.fromAHSL( + 1.0, + // Use custom hash to ensure stable value regardless of Dart changes + 360.0 * math.Random(_getColorSeed(index, level)).nextDouble(), + 1.0, + 0.7, + ).toColor(); + } + + static int _getColorSeed(int level, int index) { + // Should be no collision as long as children number < 10000. + return level * 10000 + index; + } } /// A widget ignores pointer event but still keeps semantics actions. diff --git a/packages/flutter/lib/src/widgets/sliver.dart b/packages/flutter/lib/src/widgets/sliver.dart index facab53b507..17abc49f674 100644 --- a/packages/flutter/lib/src/widgets/sliver.dart +++ b/packages/flutter/lib/src/widgets/sliver.dart @@ -1741,8 +1741,23 @@ class SliverMainAxisGroup extends MultiChildRenderObjectWidget { required List slivers, }) : super(children: slivers); + @override + MultiChildRenderObjectElement createElement() => _SliverMainAxisGroupElement(this); + @override RenderSliverMainAxisGroup createRenderObject(BuildContext context) { return RenderSliverMainAxisGroup(); } } + +class _SliverMainAxisGroupElement extends MultiChildRenderObjectElement { + _SliverMainAxisGroupElement(SliverMainAxisGroup super.widget); + + @override + void debugVisitOnstageChildren(ElementVisitor visitor) { + children.where((Element e) { + final RenderSliver renderSliver = e.renderObject! as RenderSliver; + return renderSliver.geometry!.visible; + }).forEach(visitor); + } +} diff --git a/packages/flutter/lib/src/widgets/sliver_persistent_header.dart b/packages/flutter/lib/src/widgets/sliver_persistent_header.dart index 6d3db60588a..06711dd3075 100644 --- a/packages/flutter/lib/src/widgets/sliver_persistent_header.dart +++ b/packages/flutter/lib/src/widgets/sliver_persistent_header.dart @@ -286,6 +286,8 @@ class _SliverPersistentHeaderElement extends RenderObjectElement { final SliverPersistentHeaderDelegate oldDelegate = oldWidget.delegate; if (newDelegate != oldDelegate && (newDelegate.runtimeType != oldDelegate.runtimeType || newDelegate.shouldRebuild(oldDelegate))) { + final _RenderSliverPersistentHeaderForWidgetsMixin renderObject = this.renderObject; + _updateChild(newDelegate, renderObject.lastShrinkOffset, renderObject.lastOverlapsContent); renderObject.triggerRebuild(); } } @@ -298,20 +300,19 @@ class _SliverPersistentHeaderElement extends RenderObjectElement { Element? child; + void _updateChild(SliverPersistentHeaderDelegate delegate, double shrinkOffset, bool overlapsContent) { + final Widget newWidget = delegate.build(this, shrinkOffset, overlapsContent); + child = updateChild( + child, + floating ? _FloatingHeader(child: newWidget) : newWidget, + null, + ); + } + void _build(double shrinkOffset, bool overlapsContent) { owner!.buildScope(this, () { final _SliverPersistentHeaderRenderObjectWidget sliverPersistentHeaderRenderObjectWidget = widget as _SliverPersistentHeaderRenderObjectWidget; - child = updateChild( - child, - floating - ? _FloatingHeader(child: sliverPersistentHeaderRenderObjectWidget.delegate.build( - this, - shrinkOffset, - overlapsContent - )) - : sliverPersistentHeaderRenderObjectWidget.delegate.build(this, shrinkOffset, overlapsContent), - null, - ); + _updateChild(sliverPersistentHeaderRenderObjectWidget.delegate, shrinkOffset, overlapsContent); }); } diff --git a/packages/flutter/lib/src/widgets/text.dart b/packages/flutter/lib/src/widgets/text.dart index 2768d359e47..0d39862a717 100644 --- a/packages/flutter/lib/src/widgets/text.dart +++ b/packages/flutter/lib/src/widgets/text.dart @@ -766,7 +766,7 @@ class _SelectableTextContainer extends StatefulWidget { required this.selectionColor, }); - final InlineSpan text; + final TextSpan text; final TextAlign textAlign; final TextDirection? textDirection; final bool softWrap; @@ -883,9 +883,7 @@ class _RichText extends StatelessWidget { const double _kSelectableVerticalComparingThreshold = 3.0; class _SelectableTextContainerDelegate extends StaticSelectionContainerDelegate { - _SelectableTextContainerDelegate( - GlobalKey textKey, - ) : _textKey = textKey; + _SelectableTextContainerDelegate(GlobalKey textKey) : _textKey = textKey; final GlobalKey _textKey; RenderParagraph get paragraph => _textKey.currentContext!.findRenderObject()! as RenderParagraph; @@ -1222,6 +1220,73 @@ class _SelectableTextContainerDelegate extends StaticSelectionContainerDelegate return a.right > b.right ? 1 : -1; } + /// This method calculates a local [SelectedContentRange] based on the list + /// of [selections] that are accumulated from the [Selectable] children under this + /// delegate. This calculation takes into account the accumulated content + /// length before the active selection, and returns null when either selection + /// edge has not been set. + SelectedContentRange? _calculateLocalRange(List<_SelectionInfo> selections) { + if (currentSelectionStartIndex == -1 || currentSelectionEndIndex == -1) { + return null; + } + int startOffset = 0; + int endOffset = 0; + bool foundStart = false; + bool forwardSelection = currentSelectionEndIndex >= currentSelectionStartIndex; + if (currentSelectionEndIndex == currentSelectionStartIndex) { + // Determining selection direction is innacurate if currentSelectionStartIndex == currentSelectionEndIndex. + // Use the range from the selectable within the selection as the source of truth for selection direction. + final SelectedContentRange rangeAtSelectableInSelection = selectables[currentSelectionStartIndex].getSelection()!; + forwardSelection = rangeAtSelectableInSelection.endOffset >= rangeAtSelectableInSelection.startOffset; + } + for (int index = 0; index < selections.length; index++) { + final _SelectionInfo selection = selections[index]; + if (selection.range == null) { + if (foundStart) { + return SelectedContentRange( + startOffset: forwardSelection ? startOffset : endOffset, + endOffset: forwardSelection ? endOffset : startOffset, + ); + } + startOffset += selection.contentLength; + endOffset = startOffset; + continue; + } + final int selectionStartNormalized = min(selection.range!.startOffset, selection.range!.endOffset); + final int selectionEndNormalized = max(selection.range!.startOffset, selection.range!.endOffset); + if (!foundStart) { + // Because a RenderParagraph may split its content into multiple selectables + // we have to consider at what offset a selectable starts at relative + // to the RenderParagraph, when the selectable is not the start of the content. + final bool shouldConsiderContentStart = index > 0 && paragraph.selectableBelongsToParagraph(selectables[index]); + startOffset += (selectionStartNormalized - (shouldConsiderContentStart ? paragraph.getPositionForOffset(selectables[index].boundingBoxes.first.centerLeft).offset : 0)).abs(); + endOffset = startOffset + (selectionEndNormalized - selectionStartNormalized).abs(); + foundStart = true; + } else { + endOffset += (selectionEndNormalized - selectionStartNormalized).abs(); + } + } + assert(foundStart, 'The start of the selection has not been found despite this selection delegate having an existing currentSelectionStartIndex and currentSelectionEndIndex.'); + return SelectedContentRange( + startOffset: forwardSelection ? startOffset : endOffset, + endOffset: forwardSelection ? endOffset : startOffset, + ); + } + + /// Returns a [SelectedContentRange] considering the [SelectedContentRange] + /// from each [Selectable] child managed under this delegate. + /// + /// When nothing is selected or either selection edge has not been set, + /// this method will return `null`. + @override + SelectedContentRange? getSelection() { + final List<_SelectionInfo> selections = <_SelectionInfo>[ + for (final Selectable selectable in selectables) + (contentLength: selectable.contentLength, range: selectable.getSelection()) + ]; + return _calculateLocalRange(selections); + } + // From [SelectableRegion]. // Clears the selection on all selectables not in the range of @@ -1267,3 +1332,7 @@ class _SelectableTextContainerDelegate extends StaticSelectionContainerDelegate return currentSelectionStartIndex == -1 ? _initSelection(event, isEnd: false) : _adjustSelection(event, isEnd: false); } } + +/// The length of the content that can be selected, and the range that is +/// selected. +typedef _SelectionInfo = ({int contentLength, SelectedContentRange? range}); diff --git a/packages/flutter/lib/src/widgets/text_selection.dart b/packages/flutter/lib/src/widgets/text_selection.dart index d7087c9bc90..d794c054ae1 100644 --- a/packages/flutter/lib/src/widgets/text_selection.dart +++ b/packages/flutter/lib/src/widgets/text_selection.dart @@ -696,6 +696,9 @@ class TextSelectionOverlay { // corresponds to, in global coordinates. late double _endHandleDragTarget; + // The initial selection when a selection handle drag has started. + TextSelection? _dragStartSelection; + void _handleSelectionEndHandleDragStart(DragStartDetails details) { if (!renderObject.attached) { return; @@ -721,6 +724,7 @@ class TextSelectionOverlay { centerOfLineGlobal, ), ); + _dragStartSelection ??= _selection; _selectionOverlay.showMagnifier( _buildMagnifier( @@ -760,6 +764,7 @@ class TextSelectionOverlay { if (!renderObject.attached) { return; } + assert(_dragStartSelection != null); // This is NOT the same as details.localPosition. That is relative to the // selection handle, whereas this is relative to the RenderEditable. @@ -780,7 +785,7 @@ class TextSelectionOverlay { final TextPosition position = renderObject.getPositionForPoint(handleTargetGlobal); - if (_selection.isCollapsed) { + if (_dragStartSelection!.isCollapsed) { _selectionOverlay.updateMagnifier(_buildMagnifier( currentTextPosition: position, globalGesturePosition: details.globalPosition, @@ -797,13 +802,15 @@ class TextSelectionOverlay { // On Apple platforms, dragging the base handle makes it the extent. case TargetPlatform.iOS: case TargetPlatform.macOS: + // Use this instead of _dragStartSelection.isNormalized because TextRange.isNormalized + // always returns true for a TextSelection. + final bool dragStartSelectionNormalized = _dragStartSelection!.extentOffset >= _dragStartSelection!.baseOffset; newSelection = TextSelection( + baseOffset: dragStartSelectionNormalized + ? _dragStartSelection!.baseOffset + : _dragStartSelection!.extentOffset, extentOffset: position.offset, - baseOffset: _selection.start, ); - if (position.offset <= _selection.start) { - return; // Don't allow order swapping. - } case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: @@ -859,6 +866,7 @@ class TextSelectionOverlay { centerOfLineGlobal, ), ); + _dragStartSelection ??= _selection; _selectionOverlay.showMagnifier( _buildMagnifier( @@ -873,6 +881,7 @@ class TextSelectionOverlay { if (!renderObject.attached) { return; } + assert(_dragStartSelection != null); // This is NOT the same as details.localPosition. That is relative to the // selection handle, whereas this is relative to the RenderEditable. @@ -890,7 +899,7 @@ class TextSelectionOverlay { ); final TextPosition position = renderObject.getPositionForPoint(handleTargetGlobal); - if (_selection.isCollapsed) { + if (_dragStartSelection!.isCollapsed) { _selectionOverlay.updateMagnifier(_buildMagnifier( currentTextPosition: position, globalGesturePosition: details.globalPosition, @@ -907,13 +916,15 @@ class TextSelectionOverlay { // On Apple platforms, dragging the base handle makes it the extent. case TargetPlatform.iOS: case TargetPlatform.macOS: + // Use this instead of _dragStartSelection.isNormalized because TextRange.isNormalized + // always returns true for a TextSelection. + final bool dragStartSelectionNormalized = _dragStartSelection!.extentOffset >= _dragStartSelection!.baseOffset; newSelection = TextSelection( + baseOffset: dragStartSelectionNormalized + ? _dragStartSelection!.extentOffset + : _dragStartSelection!.baseOffset, extentOffset: position.offset, - baseOffset: _selection.end, ); - if (newSelection.extentOffset >= _selection.end) { - return; // Don't allow order swapping. - } case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: @@ -940,6 +951,7 @@ class TextSelectionOverlay { if (!context.mounted) { return; } + _dragStartSelection = null; if (selectionControls is! TextSelectionHandleControls) { _selectionOverlay.hideMagnifier(); if (!_selection.isCollapsed) { @@ -1603,7 +1615,10 @@ class SelectionOverlay { Widget _buildStartHandle(BuildContext context) { final Widget handle; final TextSelectionControls? selectionControls = this.selectionControls; - if (selectionControls == null) { + if (selectionControls == null + || (_startHandleType == TextSelectionHandleType.collapsed && _isDraggingEndHandle)) { + // Hide the start handle when dragging the end handle and collapsing + // the selection. handle = const SizedBox.shrink(); } else { handle = _SelectionHandleOverlay( @@ -1629,8 +1644,11 @@ class SelectionOverlay { Widget _buildEndHandle(BuildContext context) { final Widget handle; final TextSelectionControls? selectionControls = this.selectionControls; - if (selectionControls == null || _startHandleType == TextSelectionHandleType.collapsed) { - // Hide the second handle when collapsed. + if (selectionControls == null + || (_endHandleType == TextSelectionHandleType.collapsed && _isDraggingStartHandle) + || (_endHandleType == TextSelectionHandleType.collapsed && !_isDraggingStartHandle && !_isDraggingEndHandle)) { + // Hide the end handle when dragging the start handle and collapsing the selection + // or when the selection is collapsed and no handle is being dragged. handle = const SizedBox.shrink(); } else { handle = _SelectionHandleOverlay( @@ -1857,6 +1875,24 @@ class _SelectionHandleOverlayState extends State<_SelectionHandleOverlay> with S } } + /// Returns the bounding [Rect] of the text selection handle in local + /// coordinates. + /// + /// When interacting with a text selection handle through a touch event, the + /// interactive area should be at least [kMinInteractiveDimension] square, + /// which this method does not consider. + Rect _getHandleRect(TextSelectionHandleType type, double preferredLineHeight) { + final Size handleSize = widget.selectionControls.getHandleSize( + preferredLineHeight, + ); + return Rect.fromLTWH( + 0.0, + 0.0, + handleSize.width, + handleSize.height, + ); + } + @override void didUpdateWidget(_SelectionHandleOverlay oldWidget) { super.didUpdateWidget(oldWidget); @@ -1874,20 +1910,10 @@ class _SelectionHandleOverlayState extends State<_SelectionHandleOverlay> with S @override Widget build(BuildContext context) { - final Offset handleAnchor = widget.selectionControls.getHandleAnchor( + final Rect handleRect = _getHandleRect( widget.type, widget.preferredLineHeight, ); - final Size handleSize = widget.selectionControls.getHandleSize( - widget.preferredLineHeight, - ); - - final Rect handleRect = Rect.fromLTWH( - -handleAnchor.dx, - -handleAnchor.dy, - handleSize.width, - handleSize.height, - ); // Make sure the GestureDetector is big enough to be easily interactive. final Rect interactiveRect = handleRect.expandToInclude( @@ -1900,6 +1926,11 @@ class _SelectionHandleOverlayState extends State<_SelectionHandleOverlay> with S math.max((interactiveRect.height - handleRect.height) / 2, 0), ); + final Offset handleAnchor = widget.selectionControls.getHandleAnchor( + widget.type, + widget.preferredLineHeight, + ); + // Make sure a drag is eagerly accepted. This is used on iOS to match the // behavior where a drag directly on a collapse handle will always win against // other drag gestures. @@ -1907,7 +1938,8 @@ class _SelectionHandleOverlayState extends State<_SelectionHandleOverlay> with S return CompositedTransformFollower( link: widget.handleLayerLink, - offset: interactiveRect.topLeft, + // Put the handle's anchor point on the leader's anchor point. + offset: -handleAnchor - Offset(padding.left, padding.top), showWhenUnlinked: false, child: FadeTransition( opacity: _opacity, @@ -2246,6 +2278,7 @@ class TextSelectionGestureDetectorBuilder { if (!delegate.selectionEnabled) { return; } + // TODO(Renzo-Olivares): Migrate text selection gestures away from saving state // in renderEditable. The gesture callbacks can use the details objects directly // in callbacks variants that provide them [TapGestureRecognizer.onSecondaryTap] @@ -2270,6 +2303,22 @@ class TextSelectionGestureDetectorBuilder { final bool isShiftPressedValid = _isShiftPressed && renderEditable.selection?.baseOffset != null; switch (defaultTargetPlatform) { case TargetPlatform.android: + if (editableText.widget.stylusHandwritingEnabled) { + final bool stylusEnabled = switch (kind) { + PointerDeviceKind.stylus + || PointerDeviceKind.invertedStylus => + editableText.widget.stylusHandwritingEnabled, + _ => false, + }; + if (stylusEnabled) { + Scribe.isFeatureAvailable().then((bool isAvailable) { + if (isAvailable) { + renderEditable.selectPosition(cause: SelectionChangedCause.scribble); + Scribe.startStylusHandwriting(); + } + }); + } + } case TargetPlatform.fuchsia: case TargetPlatform.iOS: // On mobile platforms the selection is set on tap up. diff --git a/packages/flutter/lib/src/widgets/undo_history.dart b/packages/flutter/lib/src/widgets/undo_history.dart index 5d0b0feb436..510503f035f 100644 --- a/packages/flutter/lib/src/widgets/undo_history.dart +++ b/packages/flutter/lib/src/widgets/undo_history.dart @@ -225,6 +225,7 @@ class UndoHistoryState extends State> with UndoManagerClient { } } + @protected @override void initState() { super.initState(); @@ -243,6 +244,7 @@ class UndoHistoryState extends State> with UndoManagerClient { _effectiveController.onRedo.addListener(redo); } + @protected @override void didUpdateWidget(UndoHistory oldWidget) { super.didUpdateWidget(oldWidget); @@ -265,6 +267,7 @@ class UndoHistoryState extends State> with UndoManagerClient { } } + @protected @override void dispose() { if (UndoManager.client == this) { @@ -280,6 +283,7 @@ class UndoHistoryState extends State> with UndoManagerClient { super.dispose(); } + @protected @override Widget build(BuildContext context) { return Actions( diff --git a/packages/flutter/lib/src/widgets/widget_inspector.dart b/packages/flutter/lib/src/widgets/widget_inspector.dart index 072b94e9209..8d80e50efce 100644 --- a/packages/flutter/lib/src/widgets/widget_inspector.dart +++ b/packages/flutter/lib/src/widgets/widget_inspector.dart @@ -37,8 +37,20 @@ import 'service_extensions.dart'; import 'view.dart'; /// Signature for the builder callback used by -/// [WidgetInspector.selectButtonBuilder]. -typedef InspectorSelectButtonBuilder = Widget Function(BuildContext context, VoidCallback onPressed); +/// [WidgetInspector.exitWidgetSelectionButtonBuilder]. +typedef ExitWidgetSelectionButtonBuilder = Widget Function( + BuildContext context, { + required VoidCallback onPressed, + required GlobalKey key, +}); + +/// Signature for the builder callback used by +/// [WidgetInspector.moveExitWidgetSelectionButtonBuilder]. +typedef MoveExitWidgetSelectionButtonBuilder = Widget Function( + BuildContext context, { + required VoidCallback onPressed, + bool isLeftAligned, +}); /// Signature for a method that registers the service extension `callback` with /// the given `name`. @@ -774,13 +786,15 @@ mixin WidgetInspectorService { static WidgetInspectorService get instance => _instance; static WidgetInspectorService _instance = _WidgetInspectorService(); - /// Whether the inspector is in select mode. + /// Enables select mode for the Inspector. /// /// In select mode, pointer interactions trigger widget selection instead of /// normal interactions. Otherwise the previously selected widget is /// highlighted but the application can be interacted with normally. @visibleForTesting - final ValueNotifier isSelectMode = ValueNotifier(true); + set isSelectMode(bool enabled) { + _changeWidgetSelectionMode(enabled); + } @protected static set instance(WidgetInspectorService instance) { @@ -1622,6 +1636,13 @@ mixin WidgetInspectorService { } } + /// Changes whether widget selection mode is [enabled]. + void _changeWidgetSelectionMode(bool enabled) { + WidgetsBinding.instance.debugShowWidgetInspectorOverride = enabled; + _postExtensionStateChangedEvent( + WidgetInspectorServiceExtensions.show.name, enabled); + } + /// Returns a DevTools uri linking to a specific element on the inspector page. String? _devToolsInspectorUriForElement(Element element) { if (activeDevToolsServerAddress != null && connectedVmServiceUri != null) { @@ -1733,7 +1754,15 @@ mixin WidgetInspectorService { bool fullDetails = true, } ) { - return node?.toJsonMap(delegate, fullDetails: fullDetails); + if (fullDetails) { + return node?.toJsonMap(delegate); + } else { + // If we don't need the full details fetched from all the subclasses, we + // can iteratively build the JSON map. This prevents a stack overflow + // exception for particularly large widget trees. For details, see: + // https://github.com/flutter/devtools/issues/8553 + return node?.toJsonMapIterative(delegate); + } } bool _isValueCreatedByLocalProject(Object? value) { @@ -1803,14 +1832,8 @@ mixin WidgetInspectorService { List nodes, InspectorSerializationDelegate delegate, { required DiagnosticsNode? parent, - bool fullDetails = true, }) { - return DiagnosticsNode.toJsonList( - nodes, - parent, - delegate, - fullDetails: fullDetails, - ); + return DiagnosticsNode.toJsonList(nodes, parent, delegate); } /// Returns a JSON representation of the properties of the [DiagnosticsNode] @@ -2758,17 +2781,28 @@ class WidgetInspector extends StatefulWidget { const WidgetInspector({ super.key, required this.child, - required this.selectButtonBuilder, + required this.exitWidgetSelectionButtonBuilder, + required this.moveExitWidgetSelectionButtonBuilder, }); /// The widget that is being inspected. final Widget child; - /// A builder that is called to create the select button. + /// A builder that is called to create the exit select-mode button. + /// + /// The `onPressed` callback and key passed as arguments to the builder should + /// be hooked up to the returned widget. + final ExitWidgetSelectionButtonBuilder? exitWidgetSelectionButtonBuilder; + + /// A builder that is called to create the button that moves the exit select- + /// mode button to the right or left. /// /// The `onPressed` callback passed as an argument to the builder should be /// hooked up to the returned widget. - final InspectorSelectButtonBuilder? selectButtonBuilder; + /// + /// The button UI should respond to the `leftAligned` argument. + final MoveExitWidgetSelectionButtonBuilder? + moveExitWidgetSelectionButtonBuilder; @override State createState() => _WidgetInspectorState(); @@ -2797,24 +2831,24 @@ class _WidgetInspectorState extends State WidgetInspectorService.instance.selection .addListener(_selectionInformationChanged); - WidgetInspectorService.instance.isSelectMode + WidgetsBinding.instance.debugShowWidgetInspectorOverrideNotifier .addListener(_selectionInformationChanged); selection = WidgetInspectorService.instance.selection; - isSelectMode = WidgetInspectorService.instance.isSelectMode.value; + isSelectMode = WidgetsBinding.instance.debugShowWidgetInspectorOverride; } @override void dispose() { WidgetInspectorService.instance.selection .removeListener(_selectionInformationChanged); - WidgetInspectorService.instance.isSelectMode + WidgetsBinding.instance.debugShowWidgetInspectorOverrideNotifier .removeListener(_selectionInformationChanged); super.dispose(); } void _selectionInformationChanged() => setState((){ selection = WidgetInspectorService.instance.selection; - isSelectMode = WidgetInspectorService.instance.isSelectMode.value; + isSelectMode = WidgetsBinding.instance.debugShowWidgetInspectorOverride; }); bool _hitTestHelper( @@ -2926,6 +2960,9 @@ class _WidgetInspectorState extends State final Rect bounds = (Offset.zero & (view.physicalSize / view.devicePixelRatio)).deflate(_kOffScreenMargin); if (!bounds.contains(_lastPointerLocation!)) { selection.clear(); + } else { + // Otherwise notify DevTools of the current selection. + WidgetInspectorService.instance._sendInspectEvent(selection.current); } } @@ -2937,22 +2974,13 @@ class _WidgetInspectorState extends State _inspectAt(_lastPointerLocation!); WidgetInspectorService.instance._sendInspectEvent(selection.current); } - - // Only exit select mode if there is a button to return to select mode. - if (widget.selectButtonBuilder != null) { - WidgetInspectorService.instance.isSelectMode.value = false; - } - } - - void _handleEnableSelect() { - WidgetInspectorService.instance.isSelectMode.value = true; } @override Widget build(BuildContext context) { // Be careful changing this build method. The _InspectorOverlayLayer // assumes the root RenderObject for the WidgetInspector will be - // a RenderStack with a _RenderInspectorOverlay as the last child. + // a RenderStack containing a _RenderInspectorOverlay as a child. return Stack(children: [ GestureDetector( onTap: _handleTap, @@ -2967,13 +2995,14 @@ class _WidgetInspectorState extends State child: widget.child, ), ), - if (!isSelectMode && widget.selectButtonBuilder != null) - Positioned( - left: _kInspectButtonMargin, - bottom: _kInspectButtonMargin, - child: widget.selectButtonBuilder!(context, _handleEnableSelect), - ), _InspectorOverlay(selection: selection), + if (isSelectMode && widget.exitWidgetSelectionButtonBuilder != null) + _ExitWidgetSelectionButtonGroup( + exitWidgetSelectionButtonBuilder: + widget.exitWidgetSelectionButtonBuilder!, + moveExitWidgetSelectionButtonBuilder: + widget.moveExitWidgetSelectionButtonBuilder, + ), ]); } } @@ -3429,7 +3458,10 @@ class _InspectorOverlayLayer extends Layer { while (current != null) { // We found the widget inspector render object. if (current is RenderStack - && current.lastChild is _RenderInspectorOverlay) { + && + current.getChildrenAsList().any( + (RenderBox child) => child is _RenderInspectorOverlay, + )) { return rootRenderObject == current; } current = current.parent; @@ -3440,7 +3472,6 @@ class _InspectorOverlayLayer extends Layer { const double _kScreenEdgeMargin = 10.0; const double _kTooltipPadding = 5.0; -const double _kInspectButtonMargin = 10.0; /// Interpret pointer up events within with this margin as indicating the /// pointer is moving off the device. @@ -3452,6 +3483,304 @@ const TextStyle _messageStyle = TextStyle( height: 1.2, ); +class _ExitWidgetSelectionButtonGroup extends StatefulWidget { + const _ExitWidgetSelectionButtonGroup({ + required this.exitWidgetSelectionButtonBuilder, + required this.moveExitWidgetSelectionButtonBuilder, + }); + + final ExitWidgetSelectionButtonBuilder exitWidgetSelectionButtonBuilder; + final MoveExitWidgetSelectionButtonBuilder? + moveExitWidgetSelectionButtonBuilder; + + @override + State<_ExitWidgetSelectionButtonGroup> createState() => + _ExitWidgetSelectionButtonGroupState(); +} + +class _ExitWidgetSelectionButtonGroupState + extends State<_ExitWidgetSelectionButtonGroup> { + static const double _kExitWidgetSelectionButtonPadding = 4.0; + static const double _kExitWidgetSelectionButtonMargin = 10.0; + + final GlobalKey _exitWidgetSelectionButtonKey = GlobalKey( + debugLabel: 'Exit Widget Selection button', + ); + + String? _tooltipMessage; + + bool _leftAligned = true; + + @override + Widget build(BuildContext context) { + final Widget? moveExitWidgetSelectionButton = + widget.moveExitWidgetSelectionButtonBuilder != null + ? Padding( + padding: EdgeInsets.only( + left: _leftAligned ? _kExitWidgetSelectionButtonPadding : 0.0, + right: + _leftAligned ? 0.0 : _kExitWidgetSelectionButtonPadding, + ), + child: _TooltipGestureDetector( + button: widget.moveExitWidgetSelectionButtonBuilder!( + context, + onPressed: () { + _changeButtonGroupAlignment(); + _onTooltipHidden(); + }, + isLeftAligned: _leftAligned, + ), + onTooltipVisible: () { + _changeTooltipMessage( + 'Move to the ${_leftAligned ? 'right' : 'left'}', + ); + }, + onTooltipHidden: _onTooltipHidden, + ), + ) + : null; + + final Widget buttonGroup = Stack( + alignment: AlignmentDirectional.topCenter, + children: [ + CustomPaint( + painter: _ExitWidgetSelectionTooltipPainter( + tooltipMessage: _tooltipMessage, + buttonKey: _exitWidgetSelectionButtonKey, + isLeftAligned: _leftAligned, + ), + ), + Row( + children: [ + if (!_leftAligned && moveExitWidgetSelectionButton != null) + moveExitWidgetSelectionButton, + _TooltipGestureDetector( + button: widget.exitWidgetSelectionButtonBuilder( + context, + onPressed: _exitWidgetSelectionMode, + key: _exitWidgetSelectionButtonKey, + ), + onTooltipVisible: () { + _changeTooltipMessage('Exit Select Widget mode'); + }, + onTooltipHidden: _onTooltipHidden, + ), + if (_leftAligned && moveExitWidgetSelectionButton != null) + moveExitWidgetSelectionButton, + ], + ), + ], + ); + + return Positioned( + left: _leftAligned ? _kExitWidgetSelectionButtonMargin : null, + right: _leftAligned ? null : _kExitWidgetSelectionButtonMargin, + bottom: _kExitWidgetSelectionButtonMargin, + child: buttonGroup, + ); + } + + void _exitWidgetSelectionMode() { + WidgetInspectorService.instance._changeWidgetSelectionMode(false); + } + + void _changeButtonGroupAlignment() { + if (mounted) { + setState(() { + _leftAligned = !_leftAligned; + }); + } + } + + void _onTooltipHidden() { + _changeTooltipMessage(null); + } + + void _changeTooltipMessage(String? message) { + if (mounted) { + setState(() { + _tooltipMessage = message; + }); + } + } +} + +class _TooltipGestureDetector extends StatefulWidget { + const _TooltipGestureDetector({ + required this.button, + required this.onTooltipVisible, + required this.onTooltipHidden, + }); + + final Widget button; + final void Function() onTooltipVisible; + final void Function() onTooltipHidden; + + static const Duration _tooltipShownOnLongPressDuration = Duration( + milliseconds: 1500, + ); + static const Duration _tooltipDelayDuration = Duration( + milliseconds: 100, + ); + + @override + State<_TooltipGestureDetector> createState() => + _TooltipGestureDetectorState(); +} + +class _TooltipGestureDetectorState extends State<_TooltipGestureDetector> { + Timer? _tooltipVisibleTimer; + Timer? _tooltipHiddenTimer; + + @override + void dispose() { + _tooltipVisibleTimer?.cancel(); + _tooltipVisibleTimer = null; + _tooltipHiddenTimer?.cancel(); + _tooltipHiddenTimer = null; + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Stack( + alignment: AlignmentDirectional.topCenter, + children: [ + GestureDetector( + onLongPress: () { + _tooltipVisibleAfter(_TooltipGestureDetector._tooltipDelayDuration); + _tooltipHiddenAfter( + _TooltipGestureDetector._tooltipShownOnLongPressDuration + + _TooltipGestureDetector._tooltipDelayDuration, + ); + }, + child: MouseRegion( + onEnter: (_) { + _tooltipVisibleAfter( + _TooltipGestureDetector._tooltipDelayDuration); + }, + onExit: (_) { + _tooltipHiddenAfter( + _TooltipGestureDetector._tooltipDelayDuration); + }, + child: widget.button, + ), + ), + ], + ); + } + + void _tooltipVisibleAfter(Duration duration) { + _tooltipVisibilityChangedAfter(duration, isVisible: true); + } + + void _tooltipHiddenAfter(Duration duration) { + _tooltipVisibilityChangedAfter(duration, isVisible: false); + } + + void _tooltipVisibilityChangedAfter( + Duration duration, { + required bool isVisible, + }) { + final Timer? timer = isVisible ? _tooltipVisibleTimer : _tooltipHiddenTimer; + if (timer?.isActive ?? false) { + timer!.cancel(); + } + + if (isVisible) { + _tooltipVisibleTimer = Timer(duration, () { + widget.onTooltipVisible(); + }); + } else { + _tooltipHiddenTimer = Timer(duration, () { + widget.onTooltipHidden(); + }); + } + } +} + +class _ExitWidgetSelectionTooltipPainter extends CustomPainter { + _ExitWidgetSelectionTooltipPainter({ + required this.tooltipMessage, + required this.buttonKey, + required this.isLeftAligned, + }); + + final String? tooltipMessage; + final GlobalKey buttonKey; + final bool isLeftAligned; + + @override + void paint(Canvas canvas, Size size) { + // Do not paint the tooltip if it is currently hidden. + final bool isVisible = tooltipMessage != null; + if (!isVisible) { + return; + } + + // Do not paint the tooltip if the exit select mode button is not rendered. + final RenderObject? buttonRenderObject = + buttonKey.currentContext?.findRenderObject(); + if (buttonRenderObject == null) { + return; + } + + // Define tooltip appearance. + const double tooltipPadding = 4.0; + const double tooltipSpacing = 6.0; + + final TextPainter tooltipTextPainter = TextPainter() + ..maxLines = 1 + ..ellipsis = '...' + ..text = TextSpan( + text: tooltipMessage, + style: _messageStyle, + ) + ..textDirection = TextDirection.ltr + ..layout(); + + final Paint tooltipPaint = Paint() + ..style = PaintingStyle.fill + ..color = _kTooltipBackgroundColor; + + // Determine tooltip position. + final double buttonWidth = buttonRenderObject.paintBounds.width; + final Size textSize = tooltipTextPainter.size; + final double textWidth = textSize.width; + final double textHeight = textSize.height; + final double tooltipWidth = textWidth + (tooltipPadding * 2); + final double tooltipHeight = textHeight + (tooltipPadding * 2); + + final double tooltipXOffset = + isLeftAligned ? 0 - buttonWidth : 0 - (tooltipWidth - buttonWidth); + final double tooltipYOffset = 0 - tooltipHeight - tooltipSpacing; + + // Draw tooltip background. + canvas.drawRect( + Rect.fromLTWH( + tooltipXOffset, + tooltipYOffset, + tooltipWidth, + tooltipHeight, + ), + tooltipPaint, + ); + + // Draw tooltip text. + tooltipTextPainter.paint( + canvas, + Offset( + tooltipXOffset + tooltipPadding, + tooltipYOffset + tooltipPadding, + )); + } + + @override + bool shouldRepaint(covariant _ExitWidgetSelectionTooltipPainter oldDelegate) { + return tooltipMessage != oldDelegate.tooltipMessage; + } +} + /// Interface for classes that track the source code location the their /// constructor was called from. /// diff --git a/packages/flutter/pubspec.yaml b/packages/flutter/pubspec.yaml index 56f07d47d76..11f89b08e35 100644 --- a/packages/flutter/pubspec.yaml +++ b/packages/flutter/pubspec.yaml @@ -3,7 +3,7 @@ description: A framework for writing Flutter applications homepage: https://flutter.dev environment: - sdk: '>=3.3.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: # To update these, use "flutter update-packages --force-upgrade". diff --git a/packages/flutter/test/animation/iteration_patterns_test.dart b/packages/flutter/test/animation/iteration_patterns_test.dart index 62c905ca47d..511c9fd8c9f 100644 --- a/packages/flutter/test/animation/iteration_patterns_test.dart +++ b/packages/flutter/test/animation/iteration_patterns_test.dart @@ -40,7 +40,7 @@ void main() { log.clear(); controller.value = 0.4; - expect(log, ['listener2', 'listener4', 'listener4']); + expect(log, ['listener2', 'listener4']); log.clear(); }); diff --git a/packages/flutter/test/cupertino/action_sheet_test.dart b/packages/flutter/test/cupertino/action_sheet_test.dart index e8c4daf212d..197bae043ce 100644 --- a/packages/flutter/test/cupertino/action_sheet_test.dart +++ b/packages/flutter/test/cupertino/action_sheet_test.dart @@ -1717,7 +1717,7 @@ void main() { // Exit animation await tester.tapAt(const Offset(20.0, 20.0)); - await tester.pumpFrames(exitRecorder.record(target), const Duration(milliseconds: 400)); + await tester.pumpFrames(exitRecorder.record(target), const Duration(milliseconds: 450)); // Action sheet has disappeared expect(find.byType(CupertinoActionSheet), findsNothing); @@ -1762,7 +1762,7 @@ void main() { // Exit animation await tester.tapAt(const Offset(20.0, 20.0)); - await tester.pumpFrames(recorder.record(target), const Duration(milliseconds: 400)); + await tester.pumpFrames(recorder.record(target), const Duration(milliseconds: 450)); // Action sheet has disappeared expect(find.byType(CupertinoActionSheet), findsNothing); @@ -1956,6 +1956,44 @@ void main() { ); }); + testWidgets('CupertinoActionSheet action cursor behavior', (WidgetTester tester) async { + const SystemMouseCursor customCursor = SystemMouseCursors.grab; + + await tester.pumpWidget( + createAppWithButtonThatLaunchesActionSheet( + CupertinoActionSheet( + title: const Text('The title'), + message: const Text('Message'), + actions: [ + CupertinoActionSheetAction( + mouseCursor: customCursor, + onPressed: () { }, + child: const Text('One'), + ), + ], + ), + ), + ); + await tester.tap(find.text('Go')); + await tester.pump(); + + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + await gesture.addPointer(location: const Offset(10, 10)); + await tester.pumpAndSettle(); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.basic, + ); + + final Offset actionSheetAction = tester.getCenter(find.text('One')); + await gesture.moveTo(actionSheetAction); + await tester.pumpAndSettle(); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + customCursor, + ); + }); + testWidgets('Action sheets emits haptic vibration on sliding into a button', (WidgetTester tester) async { int vibrationCount = 0; diff --git a/packages/flutter/test/cupertino/checkbox_test.dart b/packages/flutter/test/cupertino/checkbox_test.dart index 8363bce28f7..d105a473a2f 100644 --- a/packages/flutter/test/cupertino/checkbox_test.dart +++ b/packages/flutter/test/cupertino/checkbox_test.dart @@ -516,7 +516,7 @@ void main() { home: Center( child: CupertinoCheckbox( value: value, - onChanged: enabled ? (bool? value) => true : null, + onChanged: enabled ? (bool? value) {} : null, mouseCursor: const _CheckboxMouseCursor(), focusNode: focusNode ), diff --git a/packages/flutter/test/cupertino/dialog_test.dart b/packages/flutter/test/cupertino/dialog_test.dart index 5123fc5281a..e38b1d0f38e 100644 --- a/packages/flutter/test/cupertino/dialog_test.dart +++ b/packages/flutter/test/cupertino/dialog_test.dart @@ -679,7 +679,7 @@ void main() { expect( find.byType(CupertinoAlertDialog), - paints..rect(color: const Color(0xBF1E1E1E)), + paints..rect(color: const Color(0xCC2D2D2D)), ); }); @@ -1529,27 +1529,27 @@ void main() { await tester.pump(const Duration(milliseconds: 50)); transform = tester.widget(find.byType(Transform)); - expect(transform.transform[0], moreOrLessEquals(1.145, epsilon: 0.001)); + expect(transform.transform[0], moreOrLessEquals(1.205, epsilon: 0.001)); await tester.pump(const Duration(milliseconds: 50)); transform = tester.widget(find.byType(Transform)); - expect(transform.transform[0], moreOrLessEquals(1.044, epsilon: 0.001)); + expect(transform.transform[0], moreOrLessEquals(1.100, epsilon: 0.001)); await tester.pump(const Duration(milliseconds: 50)); transform = tester.widget(find.byType(Transform)); - expect(transform.transform[0], moreOrLessEquals(1.013, epsilon: 0.001)); + expect(transform.transform[0], moreOrLessEquals(1.043, epsilon: 0.001)); await tester.pump(const Duration(milliseconds: 50)); transform = tester.widget(find.byType(Transform)); - expect(transform.transform[0], moreOrLessEquals(1.003, epsilon: 0.001)); + expect(transform.transform[0], moreOrLessEquals(1.017, epsilon: 0.001)); await tester.pump(const Duration(milliseconds: 50)); transform = tester.widget(find.byType(Transform)); - expect(transform.transform[0], moreOrLessEquals(1.000, epsilon: 0.001)); + expect(transform.transform[0], moreOrLessEquals(1.006, epsilon: 0.001)); await tester.pump(const Duration(milliseconds: 50)); transform = tester.widget(find.byType(Transform)); - expect(transform.transform[0], moreOrLessEquals(1.000, epsilon: 0.001)); + expect(transform.transform[0], moreOrLessEquals(1.002, epsilon: 0.001)); await tester.tap(find.text('Delete')); @@ -1607,50 +1607,58 @@ void main() { await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); - expect(transition.opacity.value, moreOrLessEquals(0.081, epsilon: 0.001)); + expect(transition.opacity.value, moreOrLessEquals(0.316, epsilon: 0.001)); await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); - expect(transition.opacity.value, moreOrLessEquals(0.332, epsilon: 0.001)); + expect(transition.opacity.value, moreOrLessEquals(0.665, epsilon: 0.001)); await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); - expect(transition.opacity.value, moreOrLessEquals(0.667, epsilon: 0.001)); + expect(transition.opacity.value, moreOrLessEquals(0.856, epsilon: 0.001)); await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); - expect(transition.opacity.value, moreOrLessEquals(0.918, epsilon: 0.001)); + expect(transition.opacity.value, moreOrLessEquals(0.942, epsilon: 0.001)); await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); - expect(transition.opacity.value, moreOrLessEquals(1.0, epsilon: 0.001)); + expect(transition.opacity.value, moreOrLessEquals(0.977, epsilon: 0.001)); + + await tester.pump(const Duration(milliseconds: 50)); + transition = tester.firstWidget(fadeTransitionFinder); + expect(transition.opacity.value, moreOrLessEquals(0.991, epsilon: 0.001)); + + await tester.pump(const Duration(milliseconds: 50)); + transition = tester.firstWidget(fadeTransitionFinder); + expect(transition.opacity.value, moreOrLessEquals(0.997, epsilon: 0.001)); await tester.tap(find.text('Delete')); // Exit animation, look at reverse FadeTransition. await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); - expect(transition.opacity.value, moreOrLessEquals(1.0, epsilon: 0.001)); + expect(transition.opacity.value, moreOrLessEquals(0.997, epsilon: 0.001)); await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); - expect(transition.opacity.value, moreOrLessEquals(0.918, epsilon: 0.001)); + expect(transition.opacity.value, moreOrLessEquals(0.681, epsilon: 0.001)); await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); - expect(transition.opacity.value, moreOrLessEquals(0.667, epsilon: 0.001)); + expect(transition.opacity.value, moreOrLessEquals(0.333, epsilon: 0.001)); await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); - expect(transition.opacity.value, moreOrLessEquals(0.332, epsilon: 0.001)); + expect(transition.opacity.value, moreOrLessEquals(0.143, epsilon: 0.001)); await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); - expect(transition.opacity.value, moreOrLessEquals(0.081, epsilon: 0.001)); + expect(transition.opacity.value, moreOrLessEquals(0.057, epsilon: 0.001)); await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); - expect(transition.opacity.value, moreOrLessEquals(0.0, epsilon: 0.001)); + expect(transition.opacity.value, moreOrLessEquals(0.022, epsilon: 0.001)); }); testWidgets('Actions are accessible by key', (WidgetTester tester) async { @@ -1882,7 +1890,7 @@ void main() { await tester.pumpAndSettle(); // Should take the right side of the screen - expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(410.0, 0.0)); + expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(410.0, 0.00)); expect(tester.getBottomRight(find.byType(Placeholder)), const Offset(800.0, 600.0)); }); @@ -2063,6 +2071,7 @@ Widget createAppWithCenteredButton(Widget child) { } +@pragma('vm:entry-point') class _RestorableDialogTestWidget extends StatelessWidget { const _RestorableDialogTestWidget(); diff --git a/packages/flutter/test/cupertino/magnifier_test.dart b/packages/flutter/test/cupertino/magnifier_test.dart index cc241a31a4d..bb777a6a596 100644 --- a/packages/flutter/test/cupertino/magnifier_test.dart +++ b/packages/flutter/test/cupertino/magnifier_test.dart @@ -39,6 +39,52 @@ void main() { }); group('CupertinoTextEditingMagnifier', () { + testWidgets('Magnifier border color inherits from parent CupertinoTheme', (WidgetTester tester) async { + final Key fakeTextFieldKey = UniqueKey(); + + await tester.pumpWidget( + MaterialApp( + home: SizedBox.square( + key: fakeTextFieldKey, + dimension: 10, + child: CupertinoTheme( + data: const CupertinoThemeData(primaryColor: Colors.green), + child: Builder( + builder: (BuildContext context) { + return const Placeholder(); + }, + ), + ), + ), + ), + ); + final BuildContext context = tester.element(find.byType(Placeholder)); + + // Magnifier should be positioned directly over the red square. + final RenderBox tapPointRenderBox = + tester.firstRenderObject(find.byKey(fakeTextFieldKey)) as RenderBox; + final Rect fakeTextFieldRect = + tapPointRenderBox.localToGlobal(Offset.zero) & tapPointRenderBox.size; + + final ValueNotifier magnifier = + ValueNotifier( + MagnifierInfo( + currentLineBoundaries: fakeTextFieldRect, + fieldBounds: fakeTextFieldRect, + caretRect: fakeTextFieldRect, + // The tap position is dragBelow units below the text field. + globalGesturePosition: fakeTextFieldRect.center, + ), + ); + addTearDown(magnifier.dispose); + + await showCupertinoMagnifier(context, tester, magnifier); + + // Magnifier border color should inherit from CupertinoTheme.of(context).primaryColor. + final Color magnifierBorderColor = tester.widget(find.byType(CupertinoMagnifier)).borderSide.color; + expect(magnifierBorderColor, equals(Colors.green)); + }); + group('position', () { Offset getMagnifierPosition(WidgetTester tester) { final AnimatedPositioned animatedPositioned = diff --git a/packages/flutter/test/cupertino/popup_surface_test.dart b/packages/flutter/test/cupertino/popup_surface_test.dart new file mode 100644 index 00000000000..1998978c855 --- /dev/null +++ b/packages/flutter/test/cupertino/popup_surface_test.dart @@ -0,0 +1,384 @@ +// Copyright 2014 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. + +// This file is run as part of a reduced test set in CI on Mac and Windows +// machines. +@Tags(['reduced-test-set']) +library; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; + +class _FilterTest extends StatelessWidget { + const _FilterTest(Widget child, {this.brightness = Brightness.light}) + : _child = child; + final Brightness brightness; + final Widget _child; + + @override + Widget build(BuildContext context) { + final Size size = MediaQuery.sizeOf(context); + final double tileHeight = size.height / 4; + final double tileWidth = size.width / 8; + return CupertinoApp( + home: Stack( + fit: StackFit.expand, + children: [ + // 512 color tiles + // 4 alpha levels (0.416, 0.25, 0.5, 0.75) + for (int a = 0; a < 4; a++) + for (int h = 0; h < 8; h++) // 8 hues + for (int s = 0; s < 4; s++) // 4 saturation levels + for (int b = 0; b < 4; b++) // 4 brightness levels + Positioned( + left: h * tileWidth + b * tileWidth / 4, + top: a * tileHeight + s * tileHeight / 4, + height: tileHeight, + width: tileWidth, + child: ColoredBox( + color: HSVColor.fromAHSV( + 0.5 + a / 8, + h * 45, + 0.5 + s / 8, + 0.5 + b / 8, + ).toColor(), + ), + ), + Padding( + padding: const EdgeInsets.all(32), + child: CupertinoTheme( + data: CupertinoThemeData(brightness: brightness), + child: _child, + ), + ), + ], + ), + ); + } +} + +void main() { + void disableVibranceForTest() { + CupertinoPopupSurface.debugIsVibrancePainted = false; + addTearDown(() { + CupertinoPopupSurface.debugIsVibrancePainted = true; + }); + } + + // Golden displays the color filter effect of the CupertinoPopupSurface + // when the ambient brightness is light. + testWidgets('Brightness.light color filter', (WidgetTester tester) async { + await tester.pumpWidget( + const _FilterTest( + CupertinoPopupSurface( + blurSigma: 0, + isSurfacePainted: false, + child: SizedBox(), + ), + ), + ); + + await expectLater( + find.byType(CupertinoApp), + matchesGoldenFile('cupertinoPopupSurface.color-filter.light.png'), + ); + }, + skip: kIsWasm, // https://github.com/flutter/flutter/issues/152026 + ); + + // Golden displays the color filter effect of the CupertinoPopupSurface + // when the ambient brightness is dark. + testWidgets('Brightness.dark color filter', (WidgetTester tester) async { + await tester.pumpWidget( + const _FilterTest( + CupertinoPopupSurface( + blurSigma: 0, + isSurfacePainted: false, + child: SizedBox(), + ), + brightness: Brightness.dark, + ), + ); + + await expectLater( + find.byType(CupertinoApp), + matchesGoldenFile('cupertinoPopupSurface.color-filter.dark.png'), + ); + }, + skip: kIsWasm, // https://github.com/flutter/flutter/issues/152026 + ); + + // Golden displays color tiles without CupertinoPopupSurface being + // displayed. + testWidgets('Setting debugIsVibrancePainted to false removes the color filter', (WidgetTester tester) async { + disableVibranceForTest(); + await tester.pumpWidget( + const _FilterTest( + CupertinoPopupSurface( + blurSigma: 0, + isSurfacePainted: false, + child: SizedBox(), + ), + ), + ); + + // The BackdropFilter widget should not be mounted when blurSigma is 0 and + // CupertinoPopupSurface.debugIsVibrancePainted is false. + expect( + find.descendant( + of: find.byType(CupertinoPopupSurface), + matching: find.byType(BackdropFilter), + ), + findsNothing, + ); + + await expectLater( + find.byType(CupertinoApp), + matchesGoldenFile('cupertinoPopupSurface.color-filter.removed.png'), + ); + }); + + // Golden displays the surface color of the CupertinoPopupSurface + // in light mode. + testWidgets('Brightness.light surface color', (WidgetTester tester) async { + disableVibranceForTest(); + await tester.pumpWidget( + const _FilterTest( + CupertinoPopupSurface( + blurSigma: 0, + child: SizedBox(), + ), + ), + ); + + await expectLater( + find.byType(CupertinoApp), + matchesGoldenFile('cupertinoPopupSurface.surface-color.light.png'), + ); + }); + + // Golden displays the surface color of the CupertinoPopupSurface + // in dark mode. + testWidgets('Brightness.dark surface color', (WidgetTester tester) async { + disableVibranceForTest(); + await tester.pumpWidget( + const _FilterTest( + CupertinoPopupSurface( + blurSigma: 0, + child: SizedBox(), + ), + brightness: Brightness.dark, + ), + ); + + await expectLater( + find.byType(CupertinoApp), + matchesGoldenFile('cupertinoPopupSurface.surface-color.dark.png'), + ); + }, + ); + + // Golden displays a CupertinoPopupSurface with the color removed. The result + // should only display color tiles. + testWidgets('Setting isSurfacePainted to false removes the surface color', (WidgetTester tester) async { + disableVibranceForTest(); + await tester.pumpWidget( + const _FilterTest( + CupertinoPopupSurface( + blurSigma: 0, + isSurfacePainted: false, + child: SizedBox(), + ), + brightness: Brightness.dark, + ), + ); + + await expectLater( + find.byType(CupertinoApp), + matchesGoldenFile('cupertinoPopupSurface.surface-color.removed.png'), + ); + }, + ); + + // Goldens display a CupertinoPopupSurface with no vibrance or surface + // color, with blur sigmas of 5 and 30 (default). + testWidgets('Positive blurSigma applies blur', (WidgetTester tester) async { + disableVibranceForTest(); + await tester.pumpWidget( + const _FilterTest( + CupertinoPopupSurface( + isSurfacePainted: false, + blurSigma: 5, + child: SizedBox(), + ), + ), + ); + + await expectLater( + find.byType(CupertinoApp), + matchesGoldenFile('cupertinoPopupSurface.blur.5.png'), + ); + + await tester.pumpWidget( + const _FilterTest( + CupertinoPopupSurface( + isSurfacePainted: false, + child: SizedBox(), + ), + ), + ); + + await expectLater( + find.byType(CupertinoApp), + // 30 is the default blur sigma + matchesGoldenFile('cupertinoPopupSurface.blur.30.png'), + ); + }, + skip: kIsWasm, // https://github.com/flutter/flutter/issues/152026 + ); + + // Golden displays a CupertinoPopupSurface with a blur sigma of 0. Because + // the blur sigma is 0 and vibrance and surface are not painted, no popup + // surface is displayed. + testWidgets('Setting blurSigma to zero removes blur', (WidgetTester tester) async { + disableVibranceForTest(); + await tester.pumpWidget( + const _FilterTest( + CupertinoPopupSurface( + isSurfacePainted: false, + blurSigma: 0, + child: SizedBox(), + ), + ), + ); + + // The BackdropFilter widget should not be mounted when blurSigma is 0 and + // CupertinoPopupSurface.isVibrancePainted is false. + expect( + find.descendant( + of: find.byType(CupertinoPopupSurface), + matching: find.byType(BackdropFilter), + ), + findsNothing, + ); + + await expectLater( + find.byType(CupertinoApp), + matchesGoldenFile('cupertinoPopupSurface.blur.0.png'), + ); + + await tester.pumpWidget( + const _FilterTest( + CupertinoPopupSurface( + isSurfacePainted: false, + blurSigma: 0, + child: SizedBox(), + ), + ), + ); + }); + + testWidgets('Setting a blurSigma to a negative number throws', (WidgetTester tester) async { + try { + disableVibranceForTest(); + await tester.pumpWidget( + _FilterTest( + CupertinoPopupSurface( + isSurfacePainted: false, + blurSigma: -1, + child: const SizedBox(), + ), + ), + ); + + fail('CupertinoPopupSurface did not throw when provided a negative blur sigma.'); + } on AssertionError catch (error) { + expect( + error.toString(), + contains('CupertinoPopupSurface requires a non-negative blur sigma.'), + ); + } + }); + + // Regression test for https://github.com/flutter/flutter/issues/154887. + testWidgets("Applying a FadeTransition to the CupertinoPopupSurface doesn't cause transparency", (WidgetTester tester) async { + final AnimationController controller = AnimationController( + duration: const Duration(milliseconds: 100), + vsync: const TestVSync(), + ); + addTearDown(controller.dispose); + controller.forward(); + + await tester.pumpWidget( + _FilterTest( + FadeTransition( + opacity: controller, + child: const CupertinoPopupSurface(child: SizedBox()), + ), + ), + ); + + await tester.pump(const Duration(milliseconds: 50)); + + // Golden should display a CupertinoPopupSurface with no transparency + // directly underneath the surface. A small amount of transparency should be + // present on the upper-left corner of the screen. + // + // If transparency (gray and white grid) is present underneath the surface, + // the blendmode is being incorrectly applied. + await expectLater( + find.byType(CupertinoApp), + matchesGoldenFile('cupertinoPopupSurface.blendmode-fix.0.png'), + ); + + await tester.pumpAndSettle(); + }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); + + // Golden displays a CupertinoPopupSurface with all enabled features. + // + // CupertinoPopupSurface uses ImageFilter.compose, which applies an inner + // filter first, followed by an outer filter (e.g. result = + // outer(inner(source))). + // + // For CupertinoPopupSurface, this means that the pixels underlying the + // surface are first saturated with a ColorFilter, and the resulting saturated + // pixels are blurred with an ImageFilter.blur. This test verifies that this + // order does not change. + testWidgets('Saturation is applied before blur', (WidgetTester tester) async { + await tester.pumpWidget( + const _FilterTest( + CupertinoPopupSurface( + child: SizedBox(), + ), + ), + ); + + await expectLater( + find.byType(CupertinoApp), + matchesGoldenFile('cupertinoPopupSurface.composition.png'), + ); + + disableVibranceForTest(); + await tester.pumpWidget( + const _FilterTest( + Stack(fit: StackFit.expand, children: [ + CupertinoPopupSurface( + isSurfacePainted: false, + blurSigma: 0, + child: SizedBox(), + ), + CupertinoPopupSurface( + child: SizedBox(), + ) + ]), + ), + ); + + await expectLater( + find.byType(CupertinoApp), + matchesGoldenFile('cupertinoPopupSurface.composition.png'), + ); + }); +} diff --git a/packages/flutter/test/cupertino/route_test.dart b/packages/flutter/test/cupertino/route_test.dart index 182bf0b70d5..184eaad42a4 100644 --- a/packages/flutter/test/cupertino/route_test.dart +++ b/packages/flutter/test/cupertino/route_test.dart @@ -2691,6 +2691,54 @@ void main() { await tester.pumpAndSettle(); }); + testWidgets('fullscreen routes do not transition previous route', (WidgetTester tester) async { + await tester.pumpWidget( + CupertinoApp( + initialRoute: '/', + onGenerateRoute: (RouteSettings settings) { + if (settings.name == '/') { + return PageRouteBuilder( + pageBuilder: (BuildContext context, Animation animation, Animation secondaryAnimation) { + return CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar( + middle: Text('Page 1'), + ), + child: Container() + ); + }, + ); + } + return CupertinoPageRoute( + builder: (BuildContext context) { + return CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar( + middle: Text('Page 2'), + ), + child: Container(), + ); + }, + fullscreenDialog: true, + ); + }, + ), + ); + + expect(find.text('Page 1'), findsOneWidget); + expect(find.text('Page 2'), findsNothing); + + final double pageTitleDX = tester.getTopLeft(find.text('Page 1')).dx; + + tester.state(find.byType(Navigator)).pushNamed('/next'); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + + // Second page transition has started. + expect(find.text('Page 2'), findsOneWidget); + + // First page has not moved. + expect(tester.getTopLeft(find.text('Page 1')).dx, equals(pageTitleDX)); + }); + testWidgets('Setting CupertinoDialogRoute.requestFocus to false does not request focus on the dialog', (WidgetTester tester) async { late BuildContext savedContext; final FocusNode focusNode = FocusNode(); @@ -3129,6 +3177,7 @@ class _TestPostRouteCancelState extends State<_TestPostRouteCancel> { } } +@pragma('vm:entry-point') class _RestorableModalTestWidget extends StatelessWidget { const _RestorableModalTestWidget(); diff --git a/packages/flutter/test/cupertino/sliding_segmented_control_test.dart b/packages/flutter/test/cupertino/sliding_segmented_control_test.dart index ba558087ba3..a1892b34c13 100644 --- a/packages/flutter/test/cupertino/sliding_segmented_control_test.dart +++ b/packages/flutter/test/cupertino/sliding_segmented_control_test.dart @@ -400,7 +400,7 @@ void main() { expect(getHighlightedIndex(tester), null); }); - testWidgets('Disabled segment can be selected programmtically', (WidgetTester tester) async { + testWidgets('Disabled segment can be selected programmatically', (WidgetTester tester) async { const Map children = { 0: Text('Child 1'), 1: Text('Child 2'), diff --git a/packages/flutter/test/cupertino/text_field_test.dart b/packages/flutter/test/cupertino/text_field_test.dart index 9ea584addaa..2085a976764 100644 --- a/packages/flutter/test/cupertino/text_field_test.dart +++ b/packages/flutter/test/cupertino/text_field_test.dart @@ -503,7 +503,7 @@ void main() { ); }); - testWidgets('Activates the text field when receives semantics focus on Mac, Windows', (WidgetTester tester) async { + testWidgets('Activates the text field when receives semantics focus on desktops', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!; final FocusNode focusNode = FocusNode(); @@ -538,6 +538,7 @@ void main() { SemanticsAction.tap, SemanticsAction.focus, SemanticsAction.didGainAccessibilityFocus, + SemanticsAction.didLoseAccessibilityFocus, ], textDirection: TextDirection.ltr, ), @@ -557,8 +558,11 @@ void main() { semanticsOwner.performAction(4, SemanticsAction.didGainAccessibilityFocus); await tester.pumpAndSettle(); expect(focusNode.hasFocus, isTrue); + semanticsOwner.performAction(4, SemanticsAction.didLoseAccessibilityFocus); + await tester.pumpAndSettle(); + expect(focusNode.hasFocus, isFalse); semantics.dispose(); - }, variant: const TargetPlatformVariant({ TargetPlatform.macOS, TargetPlatform.windows })); + }, variant: TargetPlatformVariant.desktop()); testWidgets( 'takes available space horizontally and takes intrinsic space vertically no-strut', @@ -5223,7 +5227,7 @@ void main() { expect(find.byType(CupertinoButton), findsNothing); }, variant: const TargetPlatformVariant({ TargetPlatform.iOS, TargetPlatform.macOS })); - testWidgets('Cannot drag one handle past the other', (WidgetTester tester) async { + testWidgets('Cannot drag one handle past the other on non-Apple platform', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'abc def ghi', ); @@ -5231,6 +5235,8 @@ void main() { // On iOS/iPadOS, during a tap we select the edge of the word closest to the tap. // On macOS, we select the precise position of the tap. final bool isTargetPlatformIOS = defaultTargetPlatform == TargetPlatform.iOS; + // Provide a [TextSelectionControls] that builds selection handles. + final TextSelectionControls selectionControls = CupertinoTextSelectionHandleControls(); await tester.pumpWidget( CupertinoApp( @@ -5238,6 +5244,7 @@ void main() { child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, + selectionControls: selectionControls, style: const TextStyle(fontSize: 10.0), ), ), @@ -5289,7 +5296,77 @@ void main() { // The selection doesn't move beyond the left handle. There's always at // least 1 char selected. expect(controller.selection.extentOffset, 5); - }, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); + }, variant: TargetPlatformVariant.all(excluding: { TargetPlatform.iOS, TargetPlatform.macOS })); + + testWidgets('Can drag one handle past the other on iOS', (WidgetTester tester) async { + final TextEditingController controller = TextEditingController( + text: 'abc def ghi', + ); + addTearDown(controller.dispose); + // On iOS/iPadOS, during a tap we select the edge of the word closest to the tap. + // On macOS, we select the precise position of the tap. + final bool isTargetPlatformIOS = defaultTargetPlatform == TargetPlatform.iOS; + // Provide a [TextSelectionControls] that builds selection handles. + final TextSelectionControls selectionControls = CupertinoTextSelectionHandleControls(); + + await tester.pumpWidget( + CupertinoApp( + home: Center( + child: CupertinoTextField( + dragStartBehavior: DragStartBehavior.down, + controller: controller, + selectionControls: selectionControls, + style: const TextStyle(fontSize: 10.0), + ), + ), + ), + ); + + // Double tap on 'e' to select 'def'. + final Offset ePos = textOffsetToPosition(tester, 5); + await tester.tapAt(ePos, pointer: 7); + await tester.pump(const Duration(milliseconds: 50)); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, isTargetPlatformIOS ? 7 : 5); + await tester.tapAt(ePos, pointer: 7); + await tester.pumpAndSettle(); + expect(controller.selection.baseOffset, 4); + expect(controller.selection.extentOffset, 7); + + final RenderEditable renderEditable = findRenderEditable(tester); + final List endpoints = globalize( + renderEditable.getEndpointsForSelection(controller.selection), + renderEditable, + ); + expect(endpoints.length, 2); + + // On Mac, the toolbar blocks the drag on the right handle, so hide it. + final EditableTextState editableTextState = tester.state(find.byType(EditableText)); + editableTextState.hideToolbar(false); + await tester.pumpAndSettle(); + + // Drag the right handle until there's only 1 char selected. + // We use a small offset because the endpoint is on the very corner + // of the handle. + final Offset handlePos = endpoints[1].point; + Offset newHandlePos = textOffsetToPosition(tester, 5); // Position of 'e'. + final TestGesture gesture = await tester.startGesture(handlePos, pointer: 7); + await tester.pump(); + await gesture.moveTo(newHandlePos); + await tester.pump(); + expect(controller.selection.baseOffset, 4); + expect(controller.selection.extentOffset, 5); + + newHandlePos = textOffsetToPosition(tester, 2); // Position of 'c'. + await gesture.moveTo(newHandlePos); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + // The selection inverts moving beyond the left handle. + expect(controller.selection.baseOffset, 4); + expect(controller.selection.extentOffset, 2); + }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); testWidgets('Dragging between multiple lines keeps the contact point at the same place on the handle on Android', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( @@ -10385,8 +10462,13 @@ void main() { actions: [ SemanticsAction.tap, SemanticsAction.focus, - if (defaultTargetPlatform == TargetPlatform.windows || defaultTargetPlatform == TargetPlatform.macOS) - SemanticsAction.didGainAccessibilityFocus, + if (defaultTargetPlatform == TargetPlatform.linux + || defaultTargetPlatform == TargetPlatform.windows + || defaultTargetPlatform == TargetPlatform.macOS) + ...[ + SemanticsAction.didGainAccessibilityFocus, + SemanticsAction.didLoseAccessibilityFocus, + ], // TODO(gspencergoog): also test for the presence of SemanticsAction.focus when // this iOS issue is addressed: https://github.com/flutter/flutter/issues/150030 ], @@ -10442,8 +10524,13 @@ void main() { SemanticsFlag.isReadOnly, ], actions: [ - if (defaultTargetPlatform == TargetPlatform.windows || defaultTargetPlatform == TargetPlatform.macOS) - SemanticsAction.didGainAccessibilityFocus, + if (defaultTargetPlatform == TargetPlatform.linux + || defaultTargetPlatform == TargetPlatform.windows + || defaultTargetPlatform == TargetPlatform.macOS) + ...[ + SemanticsAction.didGainAccessibilityFocus, + SemanticsAction.didLoseAccessibilityFocus, + ], ], ), ], diff --git a/packages/flutter/test/cupertino/text_form_field_row_test.dart b/packages/flutter/test/cupertino/text_form_field_row_test.dart index bf1a229aacf..1065c5218c8 100644 --- a/packages/flutter/test/cupertino/text_form_field_row_test.dart +++ b/packages/flutter/test/cupertino/text_form_field_row_test.dart @@ -4,6 +4,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/rendering.dart'; +import 'package:flutter/src/services/spell_check.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -27,6 +28,29 @@ void main() { expect(textFieldWidget.textAlign, alignment); }); + testWidgets('Passes spellCheckConfiguration to underlying CupertinoTextField', (WidgetTester tester) async { + final SpellCheckConfiguration spellCheckConfig = SpellCheckConfiguration( + spellCheckService: DefaultSpellCheckService(), + misspelledSelectionColor: const Color.fromARGB(255, 255, 255, 0) + ); + + await tester.pumpWidget( + CupertinoApp( + home: Center( + child: CupertinoTextFormFieldRow( + spellCheckConfiguration: spellCheckConfig, + ), + ), + ), + ); + + final Finder textFieldFinder = find.byType(CupertinoTextField); + expect(textFieldFinder, findsOneWidget); + + final CupertinoTextField textFieldWidget = tester.widget(textFieldFinder); + expect(textFieldWidget.spellCheckConfiguration, spellCheckConfig); + }); + testWidgets('Passes scrollPhysics to underlying TextField', (WidgetTester tester) async { const ScrollPhysics scrollPhysics = ScrollPhysics(); diff --git a/packages/flutter/test/foundation/diagnostics_json_test.dart b/packages/flutter/test/foundation/diagnostics_json_test.dart index 867605d62c6..ef2969a6a8f 100644 --- a/packages/flutter/test/foundation/diagnostics_json_test.dart +++ b/packages/flutter/test/foundation/diagnostics_json_test.dart @@ -24,10 +24,15 @@ void main() { }); group('Serialization', () { - const List essentialDiagnosticKeys = [ + // These are always included. + const List defaultDiagnosticKeys = [ 'description', + ]; + // These are only included when fullDetails = false. + const List essentialDiagnosticKeys = [ 'shouldIndent', ]; + // These are only included with fullDetails = true. const List detailedDiagnosticKeys = [ 'type', 'hasChildren', @@ -81,7 +86,7 @@ void main() { expect(result.containsKey('properties'), isFalse); expect(result.containsKey('children'), isFalse); - for (final String keyName in essentialDiagnosticKeys) { + for (final String keyName in defaultDiagnosticKeys) { expect( result.containsKey(keyName), isTrue, @@ -97,15 +102,20 @@ void main() { } }); - test('without full details', () { + test('iterative implementation (without full details)', () { final Map result = testTree .toDiagnosticsNode() - .toJsonMap( - const DiagnosticsSerializationDelegate(), fullDetails: false + .toJsonMapIterative(const DiagnosticsSerializationDelegate() ); expect(result.containsKey('properties'), isFalse); expect(result.containsKey('children'), isFalse); - + for (final String keyName in defaultDiagnosticKeys) { + expect( + result.containsKey(keyName), + isTrue, + reason: '$keyName is included.', + ); + } for (final String keyName in essentialDiagnosticKeys) { expect( result.containsKey(keyName), @@ -120,6 +130,12 @@ void main() { reason: '$keyName is not included.', ); } + + // The truncated value should not be included if it is false. + expect( + result['truncated'] == null || result['truncated'] == true, + isTrue, + ); }); test('subtreeDepth 1', () { diff --git a/packages/flutter/test/material/action_chip_test.dart b/packages/flutter/test/material/action_chip_test.dart index dc974a36709..1ba6b1895dc 100644 --- a/packages/flutter/test/material/action_chip_test.dart +++ b/packages/flutter/test/material/action_chip_test.dart @@ -2,7 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:ui'; + import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; /// Adds the basic requirements for a Chip. @@ -529,4 +533,77 @@ void main() { expect(tester.widget(find.byType(RawChip)).chipAnimationStyle, chipAnimationStyle); }); + + testWidgets('ActionChip mouse cursor behavior', (WidgetTester tester) async { + const SystemMouseCursor customCursor = SystemMouseCursors.grab; + + await tester.pumpWidget(wrapForChip( + child: const Center( + child: ActionChip( + mouseCursor: customCursor, + label: Text('Chip'), + ), + ), + )); + + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + await gesture.addPointer(location: const Offset(10, 10)); + await tester.pump(); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.basic, + ); + + final Offset chip = tester.getCenter(find.text('Chip')); + await gesture.moveTo(chip); + await tester.pump(); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + customCursor, + ); + }); + + testWidgets('Mouse cursor resolves in focused/unfocused/disabled states', (WidgetTester tester) async { + tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; + final FocusNode focusNode = FocusNode(debugLabel: 'Chip'); + addTearDown(focusNode.dispose); + + Widget buildChip({ required bool enabled }) { + return wrapForChip( + child: Center( + child: ActionChip( + mouseCursor: const WidgetStateMouseCursor.fromMap( + { + WidgetState.disabled: SystemMouseCursors.forbidden, + WidgetState.focused: SystemMouseCursors.grab, + WidgetState.any: SystemMouseCursors.basic, + }, + ), + focusNode: focusNode, + label: const Text('Chip'), + onPressed: enabled ? () {} : null, + ), + ), + ); + } + + await tester.pumpWidget(buildChip(enabled: true)); + + // Unfocused case. + final TestGesture gesture1 = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + addTearDown(gesture1.removePointer); + await gesture1.addPointer(location: tester.getCenter(find.text('Chip'))); + await tester.pump(); + await gesture1.moveTo(tester.getCenter(find.text('Chip'))); + expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); + + // Focused case. + focusNode.requestFocus(); + await tester.pump(); + expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.grab); + + // Disabled case. + await tester.pumpWidget(buildChip(enabled: false)); + expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden); + }); } diff --git a/packages/flutter/test/material/app_bar_sliver_test.dart b/packages/flutter/test/material/app_bar_sliver_test.dart index f1de2c04d97..94b8f7bc5ee 100644 --- a/packages/flutter/test/material/app_bar_sliver_test.dart +++ b/packages/flutter/test/material/app_bar_sliver_test.dart @@ -2274,6 +2274,53 @@ void main() { expect(navToolBar.middleSpacing, NavigationToolbar.kMiddleSpacing); }); + // Regression test for https://github.com/flutter/flutter/issues/158158. + testWidgets('SliverAppBar should update TabBar before TabBar build', (WidgetTester tester) async { + final List tabs = []; + + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return DefaultTabController( + length: tabs.length, + child: Scaffold( + body: CustomScrollView( + slivers: [ + SliverAppBar( + actions: [ + TextButton( + child: const Text('Add Tab'), + onPressed: () { + setState(() { + tabs.add(Tab(text: 'Tab ${tabs.length + 1}')); + }); + }, + ), + ], + bottom: TabBar(tabs: tabs), + ), + ], + ), + ), + ); + }, + ), + ), + ); + + // Initializes with zero tabs. + expect(find.text('Tab 1'), findsNothing); + expect(find.text('Tab 2'), findsNothing); + + // No crash after tabs added. + await tester.tap(find.text('Add Tab')); + await tester.pumpAndSettle(); + expect(find.text('Tab 1'), findsOneWidget); + expect(find.text('Tab 2'), findsNothing); + expect(tester.takeException(), isNull); + }); + group('Material 2', () { // These tests are only relevant for Material 2. Once Material 2 // support is deprecated and the APIs are removed, these tests diff --git a/packages/flutter/test/material/calendar_date_picker_test.dart b/packages/flutter/test/material/calendar_date_picker_test.dart index d166040f844..20edff6c3b5 100644 --- a/packages/flutter/test/material/calendar_date_picker_test.dart +++ b/packages/flutter/test/material/calendar_date_picker_test.dart @@ -1196,7 +1196,7 @@ void main() { await gesture.moveTo(tester.getCenter(find.text('25'))); await tester.pumpAndSettle(); inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); - expect(inkFeatures, paints..circle(radius: 35.0, color: theme.colorScheme.onSurfaceVariant.withOpacity(0.08))); + expect(inkFeatures, paints..circle()..circle(radius: 35.0, color: theme.colorScheme.onSurfaceVariant.withOpacity(0.08))); expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 1)); final Rect expectedClipRect = Rect.fromCircle(center: const Offset(400.0, 241.0), radius: 35.0); diff --git a/packages/flutter/test/material/chip_test.dart b/packages/flutter/test/material/chip_test.dart index 029b8c2221a..ea8fbde35b1 100644 --- a/packages/flutter/test/material/chip_test.dart +++ b/packages/flutter/test/material/chip_test.dart @@ -12,6 +12,7 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import '../widgets/feedback_tester.dart'; import '../widgets/semantics_tester.dart'; @@ -6039,6 +6040,104 @@ void main() { expect(tester.widget(find.byType(RawChip)).chipAnimationStyle, chipAnimationStyle); }); + + // Regression test for https://github.com/flutter/flutter/issues/157622. + testWidgets('Chip does not glitch on hover when providing ThemeData.hoverColor', (WidgetTester tester) async { + const Color themeDataHoverColor = Color(0xffff0000); + const Color hoverColor = Color(0xff00ff00); + const Color backgroundColor = Color(0xff0000ff); + await tester.pumpWidget(wrapForChip( + theme: ThemeData(hoverColor: themeDataHoverColor), + child: Center( + child: RawChip( + color: WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.hovered)) { + return hoverColor; + } + return backgroundColor; + }), + label: const Text('Chip'), + onPressed: () {}, + ), + ), + )); + + expect(getMaterialBox(tester), paints..rrect(color: backgroundColor)); + + // Hover over the chip. + final Offset center = tester.getCenter(find.byType(RawChip)); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); + await gesture.addPointer(); + await gesture.moveTo(center); + addTearDown(gesture.removePointer); + await tester.pumpAndSettle(); + + expect( + getMaterialBox(tester), + paints..rrect(color: hoverColor)..rect(color: Colors.transparent), + ); + expect( + getMaterialBox(tester), + isNot(paints..rrect(color: hoverColor)..rect(color: themeDataHoverColor)), + ); + }); + + testWidgets('Chip mouse cursor behavior', (WidgetTester tester) async { + const SystemMouseCursor customCursor = SystemMouseCursors.grab; + + await tester.pumpWidget(wrapForChip( + child: const Center( + child: Chip( + mouseCursor: customCursor, + label: Text('Chip'), + ), + ), + )); + + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + await gesture.addPointer(location: const Offset(10, 10)); + await tester.pump(); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.basic, + ); + + final Offset chip = tester.getCenter(find.text('Chip')); + await gesture.moveTo(chip); + await tester.pump(); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + customCursor, + ); + }); + + testWidgets('Mouse cursor resolves in disabled states', (WidgetTester tester) async { + tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; + + await tester.pumpWidget( + wrapForChip( + child: const Center( + child: Chip( + mouseCursor: WidgetStateMouseCursor.fromMap( + { + WidgetState.disabled: SystemMouseCursors.forbidden, + }, + ), + label: Text('Chip'), + ), + ), + ), + ); + // Unfocused case. + final TestGesture gesture1 = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + addTearDown(gesture1.removePointer); + await gesture1.addPointer(location: tester.getCenter(find.text('Chip'))); + await tester.pump(); + await gesture1.moveTo(tester.getCenter(find.text('Chip'))); + expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden); + }); } class _MaterialStateOutlinedBorder extends StadiumBorder implements MaterialStateOutlinedBorder { diff --git a/packages/flutter/test/material/choice_chip_test.dart b/packages/flutter/test/material/choice_chip_test.dart index 76ae42cfd12..8bb26081b74 100644 --- a/packages/flutter/test/material/choice_chip_test.dart +++ b/packages/flutter/test/material/choice_chip_test.dart @@ -2,7 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:ui'; + import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; RenderBox getMaterialBox(WidgetTester tester, Finder type) { @@ -813,4 +817,79 @@ void main() { expect(tester.widget(find.byType(RawChip)).chipAnimationStyle, chipAnimationStyle); }); + + testWidgets('ChoiceChip mouse cursor behavior', (WidgetTester tester) async { + const SystemMouseCursor customCursor = SystemMouseCursors.grab; + + await tester.pumpWidget(wrapForChip( + child: const Center( + child: ChoiceChip( + selected: false, + mouseCursor: customCursor, + label: Text('Chip'), + ), + ), + )); + + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + await gesture.addPointer(location: const Offset(10, 10)); + await tester.pump(); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.basic, + ); + + final Offset chip = tester.getCenter(find.text('Chip')); + await gesture.moveTo(chip); + await tester.pump(); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + customCursor, + ); + }); + + testWidgets('Mouse cursor resolves in focused/unfocused/disabled states', (WidgetTester tester) async { + tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; + final FocusNode focusNode = FocusNode(debugLabel: 'Chip'); + addTearDown(focusNode.dispose); + + Widget buildChip({ required bool enabled }) { + return wrapForChip( + child: Center( + child: ChoiceChip( + mouseCursor: const WidgetStateMouseCursor.fromMap( + { + WidgetState.disabled: SystemMouseCursors.forbidden, + WidgetState.focused: SystemMouseCursors.grab, + WidgetState.selected: SystemMouseCursors.click, + WidgetState.any: SystemMouseCursors.basic, + }, + ), + focusNode: focusNode, + label: const Text('Chip'), + onSelected: enabled ? (bool value) {} : null, + selected: false, + ), + ), + ); + } + + // Unfocused case. + await tester.pumpWidget(buildChip(enabled: true)); + final TestGesture gesture1 = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + addTearDown(gesture1.removePointer); + await gesture1.addPointer(location: tester.getCenter(find.text('Chip'))); + await tester.pump(); + await gesture1.moveTo(tester.getCenter(find.text('Chip'))); + expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); + + // Focused case. + focusNode.requestFocus(); + await tester.pump(); + expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.grab); + + // Disabled case. + await tester.pumpWidget(buildChip(enabled: false)); + expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden); + }); } diff --git a/packages/flutter/test/material/data_table_test.dart b/packages/flutter/test/material/data_table_test.dart index cabf72c656b..a1035fd7b07 100644 --- a/packages/flutter/test/material/data_table_test.dart +++ b/packages/flutter/test/material/data_table_test.dart @@ -2417,6 +2417,92 @@ void main() { headerCenter = tester.getCenter(find.text('Header')); expect(headerCenter.dx, equals(400)); }); + + testWidgets('DataTable with custom column widths - checkbox', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: SizedBox( + width: 500, + child: DataTable( + columns: const [ + DataColumn( + label: Text('Flex Numeric'), + columnWidth: FlexColumnWidth(), + numeric: true, + ), + DataColumn( + label: Text('Numeric'), + numeric: true, + ), + DataColumn( + label: Text('Text'), + ), + ], + rows: [ + DataRow( + onSelectChanged: (bool? value) {}, + cells: const [ + DataCell(Text('1')), + DataCell(Text('1')), + DataCell(Text('D')), + ], + ), + ], + ), + ), + ), + ) + ); + + final Table table = tester.widget(find.byType(Table)); + expect(table.columnWidths![0], isA()); // Checkbox column + expect(table.columnWidths![1], const FlexColumnWidth()); + expect(table.columnWidths![2], const IntrinsicColumnWidth()); + expect(table.columnWidths![3], const IntrinsicColumnWidth(flex: 1)); + }); + + testWidgets('DataTable with custom column widths - no checkbox', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: SizedBox( + width: 500, + child: DataTable( + columns: const [ + DataColumn( + label: Text('Flex Numeric'), + columnWidth: FlexColumnWidth(), + numeric: true, + ), + DataColumn( + label: Text('Numeric'), + numeric: true, + ), + DataColumn( + label: Text('Text'), + ), + ], + rows: const [ + DataRow( + cells: [ + DataCell(Text('1')), + DataCell(Text('1')), + DataCell(Text('D')), + ], + ), + ], + ), + ), + ), + ) + ); + + final Table table = tester.widget(find.byType(Table)); + expect(table.columnWidths![0], const FlexColumnWidth()); + expect(table.columnWidths![1], const IntrinsicColumnWidth()); + expect(table.columnWidths![2], const IntrinsicColumnWidth(flex: 1)); + }); } RenderParagraph _getTextRenderObject(WidgetTester tester, String text) { diff --git a/packages/flutter/test/material/date_picker_test.dart b/packages/flutter/test/material/date_picker_test.dart index 380372d0390..251f61355da 100644 --- a/packages/flutter/test/material/date_picker_test.dart +++ b/packages/flutter/test/material/date_picker_test.dart @@ -132,6 +132,21 @@ void main() { await callback(date); } + ShapeDecoration? findDayDecoration(WidgetTester tester, String day) { + return tester.widget( + find.ancestor( + of: find.text(day), + matching: find.byType(Ink) + ), + ).decoration as ShapeDecoration?; + } + + MaterialInkController findDayGridMaterial(WidgetTester tester) { + // All days are painted on the same Material widget. + // Use an arbitrary day to find this Material. + return Material.of(tester.element(find.text('17'))); + } + group('showDatePicker Dialog', () { testWidgets('Default dialog size', (WidgetTester tester) async { Future showPicker(WidgetTester tester, Size size) async { @@ -1264,43 +1279,170 @@ void main() { await tester.pump(); const Color todayColor = Color(0xff2196f3); // default primary color expect( - Material.of(tester.element(find.text('2'))), + findDayGridMaterial(tester), // The current day should be painted with a circle outline paints..circle(color: todayColor, style: PaintingStyle.stroke, strokeWidth: 1.0), ); }); }); - testWidgets('Date picker dayOverlayColor resolves pressed state', (WidgetTester tester) async { - today = DateTime(2023, 5, 4); + testWidgets('Date picker dayOverlayColor resolves hovered state', (WidgetTester tester) async { final ThemeData theme = ThemeData(); - final bool material3 = theme.useMaterial3; - await prepareDatePicker(tester, (Future date) async { - await tester.pump(); + await prepareDatePicker(tester, (Future date) async {}, theme: theme); - // Hovered. - final Offset center = tester.getCenter(find.text('30')); - final TestGesture gesture = await tester.createGesture( - kind: PointerDeviceKind.mouse, - ); - await gesture.addPointer(); - await gesture.moveTo(center); - await tester.pumpAndSettle(); - expect( - Material.of(tester.element(find.text('30'))), - paints..circle(color: material3 ? theme.colorScheme.onSurfaceVariant.withOpacity(0.08) : theme.colorScheme.onSurfaceVariant.withOpacity(0.08)), - ); + final Offset center = tester.getCenter(find.text('30')); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); + await gesture.addPointer(); + addTearDown(gesture.removePointer); + await gesture.moveTo(center); + await tester.pumpAndSettle(); - // Highlighted (pressed). - await gesture.down(center); - await tester.pumpAndSettle(); - expect( - Material.of(tester.element(find.text('30'))), - paints..circle()..circle(color: material3 ? theme.colorScheme.onSurfaceVariant.withOpacity(0.1) : theme.colorScheme.onSurfaceVariant.withOpacity(0.12)) - ); - await gesture.up(); - await tester.pumpAndSettle(); - }, theme: theme); + expect( + findDayGridMaterial(tester), + paints + ..circle() // Today decoration. + ..circle() // Selected day decoration. + ..circle(color: theme.colorScheme.onSurfaceVariant.withOpacity(0.08)), + ); + }); + + testWidgets('Date picker dayOverlayColor resolves focused state', (WidgetTester tester) async { + FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; + final ThemeData theme = ThemeData(); + await prepareDatePicker(tester, (Future date) async {}, theme: theme); + + // Navigate to the grid. + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + + // Navigate to day 30. + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pumpAndSettle(); + + expect( + findDayGridMaterial(tester), + paints + ..circle() // Today decoration. + ..circle() // Selected day decoration. + ..circle(color: theme.colorScheme.onSurfaceVariant.withOpacity(0.10)), + ); + }); + + testWidgets('Date picker dayOverlayColor resolves pressed state', (WidgetTester tester) async { + final ThemeData theme = ThemeData(); + await prepareDatePicker(tester, (Future date) async {}, theme: theme); + + final Offset center = tester.getCenter(find.text('30')); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); + await gesture.addPointer(); + addTearDown(gesture.removePointer); + await gesture.down(center); + await tester.pumpAndSettle(); + + expect( + findDayGridMaterial(tester), + paints + ..circle() // Today decoration. + ..circle() // Selected day decoration. + ..circle() // Hovered decoration. + ..circle(color: theme.colorScheme.onSurfaceVariant.withOpacity(0.10)), + ); + await gesture.up(); + }); + + // Regression test for https://github.com/flutter/flutter/issues/130586. + testWidgets('Date picker dayOverlayColor resolves selected and hovered state', (WidgetTester tester) async { + final ThemeData theme = ThemeData(); + await prepareDatePicker(tester, (Future date) async {}, theme: theme); + + // Select day 30. + await tester.tap(find.text('30')); + await tester.pumpAndSettle(); + final ShapeDecoration day30Decoration = findDayDecoration(tester, '30')!; + expect(day30Decoration.color, theme.colorScheme.primary); + + final Offset center = tester.getCenter(find.text('30')); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); + await gesture.addPointer(); + addTearDown(gesture.removePointer); + await gesture.moveTo(center); + await tester.pumpAndSettle(); + + expect( + findDayGridMaterial(tester), + paints + ..circle() // Today decoration. + ..circle() // Selected day decoration. + ..circle(color: theme.colorScheme.onPrimary.withOpacity(0.08)), + ); + }); + + testWidgets('Date picker dayOverlayColor resolves selected and focused state', (WidgetTester tester) async { + FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; + final ThemeData theme = ThemeData(); + await prepareDatePicker(tester, (Future date) async {}, theme: theme); + + // Select day 30. + await tester.tap(find.text('30')); + await tester.pumpAndSettle(); + final ShapeDecoration day30Decoration = findDayDecoration(tester, '30')!; + expect(day30Decoration.color, theme.colorScheme.primary); + + // Navigate to the grid. + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pumpAndSettle(); + + // Day 30 is selected and focused. + expect( + findDayGridMaterial(tester), + paints + ..circle() // Today decoration. + ..circle() // Selected day decoration. + ..circle(color: theme.colorScheme.onPrimary.withOpacity(0.10)), + ); + }); + + testWidgets('Date picker dayOverlayColor resolves selected and pressed state', (WidgetTester tester) async { + final ThemeData theme = ThemeData(); + await prepareDatePicker(tester, (Future date) async {}, theme: theme); + + // Select day 30. + await tester.tap(find.text('30')); + await tester.pumpAndSettle(); + final ShapeDecoration day30Decoration = findDayDecoration(tester, '30')!; + expect(day30Decoration.color, theme.colorScheme.primary); + + final Offset center = tester.getCenter(find.text('30')); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); + await gesture.addPointer(); + addTearDown(gesture.removePointer); + await gesture.down(center); + await tester.pumpAndSettle(); + + expect( + findDayGridMaterial(tester), + paints + ..circle() // Today decoration. + ..circle() // Selected day decoration. + ..circle() // Hovered decoration. + ..circle(color: theme.colorScheme.onPrimary.withOpacity(0.10)), + ); + await gesture.up(); }); testWidgets('Selecting date does not switch picker to year selection', (WidgetTester tester) async { @@ -2306,6 +2448,164 @@ void main() { }); }); }); + + testWidgets('Date picker dayOverlayColor resolves hovered state', (WidgetTester tester) async { + final ThemeData theme = ThemeData(useMaterial3: false); + await prepareDatePicker(tester, (Future date) async {}, theme: theme); + + final Offset center = tester.getCenter(find.text('30')); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); + await gesture.addPointer(); + await gesture.moveTo(center); + await tester.pumpAndSettle(); + + expect( + findDayGridMaterial(tester), + paints + ..circle() // Today decoration. + ..circle() // Selected day decoration. + ..circle(color: theme.colorScheme.onSurfaceVariant.withOpacity(0.08)), + ); + }); + + testWidgets('Date picker dayOverlayColor resolves focused state', (WidgetTester tester) async { + FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; + final ThemeData theme = ThemeData(useMaterial3: false); + await prepareDatePicker(tester, (Future date) async {}, theme: theme); + + // Navigate to the grid. + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + + // Navigate to day 30. + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pumpAndSettle(); + + expect( + findDayGridMaterial(tester), + paints + ..circle() // Today decoration. + ..circle() // Selected day decoration. + ..circle(color: theme.colorScheme.onSurfaceVariant.withOpacity(0.12)), + ); + }); + + testWidgets('Date picker dayOverlayColor resolves pressed state', (WidgetTester tester) async { + final ThemeData theme = ThemeData(useMaterial3: false); + await prepareDatePicker(tester, (Future date) async {}, theme: theme); + + final Offset center = tester.getCenter(find.text('30')); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); + await gesture.addPointer(); + addTearDown(gesture.removePointer); + await gesture.down(center); + await tester.pumpAndSettle(); + + expect( + findDayGridMaterial(tester), + paints + ..circle() // Today decoration. + ..circle() // Selected day decoration. + ..circle() // Hovered decoration. + ..circle(color: theme.colorScheme.onSurfaceVariant.withOpacity(0.12)), + ); + await gesture.up(); + }); + + // Regression test for https://github.com/flutter/flutter/issues/130586. + testWidgets('Date picker dayOverlayColor resolves selected and hovered state', (WidgetTester tester) async { + final ThemeData theme = ThemeData(useMaterial3: false); + await prepareDatePicker(tester, (Future date) async {}, theme: theme); + + // Select day 30. + await tester.tap(find.text('30')); + await tester.pumpAndSettle(); + final ShapeDecoration day30Decoration = findDayDecoration(tester, '30')!; + expect(day30Decoration.color, theme.colorScheme.primary); + + final Offset center = tester.getCenter(find.text('30')); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); + await gesture.addPointer(); + addTearDown(gesture.removePointer); + await gesture.moveTo(center); + await tester.pumpAndSettle(); + + expect( + findDayGridMaterial(tester), + paints + ..circle() // Today decoration. + ..circle() // Selected day decoration. + ..circle(color: theme.colorScheme.onPrimary.withOpacity(0.08)), + ); + }); + + testWidgets('Date picker dayOverlayColor resolves selected and focused state', (WidgetTester tester) async { + FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; + final ThemeData theme = ThemeData(useMaterial3: false); + await prepareDatePicker(tester, (Future date) async {}, theme: theme); + + // Select day 30. + await tester.tap(find.text('30')); + await tester.pumpAndSettle(); + final ShapeDecoration day30Decoration = findDayDecoration(tester, '30')!; + expect(day30Decoration.color, theme.colorScheme.primary); + + // Navigate to the grid. + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pumpAndSettle(); + + // Day 30 is selected and focused. + expect( + findDayGridMaterial(tester), + paints + ..circle() // Today decoration. + ..circle() // Selected day decoration. + ..circle(color: theme.colorScheme.onPrimary.withOpacity(0.12)), + ); + }); + + testWidgets('Date picker dayOverlayColor resolves selected and pressed state', (WidgetTester tester) async { + final ThemeData theme = ThemeData(useMaterial3: false); + await prepareDatePicker(tester, (Future date) async {}, theme: theme); + + // Select day 30. + await tester.tap(find.text('30')); + await tester.pumpAndSettle(); + final ShapeDecoration day30Decoration = findDayDecoration(tester, '30')!; + expect(day30Decoration.color, theme.colorScheme.primary); + + final Offset center = tester.getCenter(find.text('30')); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); + await gesture.addPointer(); + addTearDown(gesture.removePointer); + await gesture.down(center); + await tester.pumpAndSettle(); + + expect( + findDayGridMaterial(tester), + paints + ..circle() // Today decoration. + ..circle() // Selected day decoration. + ..circle() // Hovered decoration. + ..circle(color: theme.colorScheme.onPrimary.withOpacity(0.38)), + ); + await gesture.up(); + }); }); } @@ -2320,6 +2620,7 @@ class _RestorableDatePickerDialogTestWidget extends StatefulWidget { _RestorableDatePickerDialogTestWidgetState createState() => _RestorableDatePickerDialogTestWidgetState(); } +@pragma('vm:entry-point') class _RestorableDatePickerDialogTestWidgetState extends State<_RestorableDatePickerDialogTestWidget> with RestorationMixin { @override String? get restorationId => 'scaffold_state'; diff --git a/packages/flutter/test/material/date_picker_theme_test.dart b/packages/flutter/test/material/date_picker_theme_test.dart index 0f949a6a1e8..28a328d364b 100644 --- a/packages/flutter/test/material/date_picker_theme_test.dart +++ b/packages/flutter/test/material/date_picker_theme_test.dart @@ -82,10 +82,10 @@ void main() { } ShapeDecoration? findDayDecoration(WidgetTester tester, String day) { - return tester.widget( + return tester.widget( find.ancestor( of: find.text(day), - matching: find.byType(DecoratedBox) + matching: find.byType(Ink) ), ).decoration as ShapeDecoration?; } @@ -756,7 +756,6 @@ void main() { datePickerTheme: DatePickerThemeData( dayOverlayColor: dayOverlayColor, ), - useMaterial3: true, ), home: Directionality( textDirection: TextDirection.ltr, @@ -776,17 +775,25 @@ void main() { ), ); + MaterialInkController findDayGridMaterial(WidgetTester tester) { + // All days are painted on the same Material widget. + // Use an arbitrary day to find this Material. + return Material.of(tester.element(find.text('17'))); + } + // Test the hover overlay color. - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.text('20'))); await tester.pumpAndSettle(); + expect( - inkFeatures, + findDayGridMaterial(tester), paints + ..circle() // Today decoration. + ..circle() // Selected day decoration. ..circle(color: dayOverlayColor.resolve({MaterialState.hovered})), ); @@ -796,16 +803,20 @@ void main() { if (kIsWeb) { // An extra circle is painted on the web for the hovered state. expect( - inkFeatures, + findDayGridMaterial(tester), paints + ..circle() // Today decoration. + ..circle() // Selected day decoration. ..circle(color: dayOverlayColor.resolve({MaterialState.hovered})) ..circle(color: dayOverlayColor.resolve({MaterialState.hovered})) ..circle(color: dayOverlayColor.resolve({MaterialState.pressed})), ); } else { expect( - inkFeatures, + findDayGridMaterial(tester), paints + ..circle() // Today decoration. + ..circle() // Selected day decoration. ..circle(color: dayOverlayColor.resolve({MaterialState.hovered})) ..circle(color: dayOverlayColor.resolve({MaterialState.pressed})), ); @@ -822,8 +833,10 @@ void main() { // Test the focused overlay color. expect( - inkFeatures, + findDayGridMaterial(tester), paints + ..circle() // Today decoration. + ..circle() // Selected day decoration. ..circle(color: dayOverlayColor.resolve({MaterialState.focused})), ); }); diff --git a/packages/flutter/test/material/date_range_picker_test.dart b/packages/flutter/test/material/date_range_picker_test.dart index cbe73bdcc7e..06518280730 100644 --- a/packages/flutter/test/material/date_range_picker_test.dart +++ b/packages/flutter/test/material/date_range_picker_test.dart @@ -1785,6 +1785,7 @@ class _RestorableDateRangePickerDialogTestWidget extends StatefulWidget { _RestorableDateRangePickerDialogTestWidgetState createState() => _RestorableDateRangePickerDialogTestWidgetState(); } +@pragma('vm:entry-point') class _RestorableDateRangePickerDialogTestWidgetState extends State<_RestorableDateRangePickerDialogTestWidget> with RestorationMixin { @override String? get restorationId => 'scaffold_state'; diff --git a/packages/flutter/test/material/dialog_test.dart b/packages/flutter/test/material/dialog_test.dart index 9c0db0b2b8b..42b9d4a731b 100644 --- a/packages/flutter/test/material/dialog_test.dart +++ b/packages/flutter/test/material/dialog_test.dart @@ -2975,6 +2975,7 @@ void main() { }); } +@pragma('vm:entry-point') class _RestorableDialogTestWidget extends StatelessWidget { const _RestorableDialogTestWidget(); diff --git a/packages/flutter/test/material/dropdown_form_field_test.dart b/packages/flutter/test/material/dropdown_form_field_test.dart index f769e068ac5..d47d96e664a 100644 --- a/packages/flutter/test/material/dropdown_form_field_test.dart +++ b/packages/flutter/test/material/dropdown_form_field_test.dart @@ -4,7 +4,6 @@ import 'dart:math' as math; -import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -1130,103 +1129,6 @@ void main() { ); }); - testWidgets('InputDecoration borders are used for clipping', (WidgetTester tester) async { - const BorderRadius errorBorderRadius = BorderRadius.all(Radius.circular(5.0)); - const BorderRadius focusedErrorBorderRadius = BorderRadius.all(Radius.circular(6.0)); - const BorderRadius focusedBorder = BorderRadius.all(Radius.circular(7.0)); - const BorderRadius enabledBorder = BorderRadius.all(Radius.circular(9.0)); - - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - - const String errorText = 'This is an error'; - bool showError = false; - - await tester.pumpWidget( - MaterialApp( - theme: ThemeData( - inputDecorationTheme: const InputDecorationTheme( - errorBorder: OutlineInputBorder( - borderRadius: errorBorderRadius, - ), - focusedErrorBorder: OutlineInputBorder( - borderRadius: focusedErrorBorderRadius, - ), - focusedBorder: OutlineInputBorder( - borderRadius: focusedBorder, - ), - enabledBorder: OutlineInputBorder( - borderRadius: enabledBorder, - ), - ), - ), - home: Material( - child: Center( - child: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return DropdownButtonFormField( - value: 'two', - onChanged:(String? value) { - setState(() { - if (value == 'three') { - showError = true; - } else { - showError = false; - } - }); - }, - decoration: InputDecoration( - errorText: showError ? errorText : null, - ), - focusNode: focusNode, - items: menuItems.map>((String item) { - return DropdownMenuItem( - key: ValueKey(item), - value: item, - child: Text(item, key: ValueKey('${item}Text')), - ); - }).toList(), - ); - } - ), - ), - ), - ), - ); - - // Test enabled border. - InkWell inkWell = tester.widget(find.byType(InkWell)); - expect(inkWell.borderRadius, enabledBorder); - - // Test focused border. - focusNode.requestFocus(); - await tester.pump(); - - inkWell = tester.widget(find.byType(InkWell)); - expect(inkWell.borderRadius, focusedBorder); - - // Test focused error border. - await tester.tap(find.text('two'), warnIfMissed: false); - await tester.pumpAndSettle(); - await tester.tap(find.text('three').last); - await tester.pumpAndSettle(); - - inkWell = tester.widget(find.byType(InkWell)); - expect(inkWell.borderRadius, focusedErrorBorderRadius); - - // Test error border with no focus. - focusNode.unfocus(); - await tester.pump(); - - // Hovering over the widget should show the error border. - final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); - await gesture.moveTo(tester.getCenter(find.text('three').last)); - await tester.pumpAndSettle(); - - inkWell = tester.widget(find.byType(InkWell)); - expect(inkWell.borderRadius, errorBorderRadius); - }); - testWidgets('DropdownButtonFormField onChanged is called when the form is reset', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/123009. final GlobalKey> stateKey = GlobalKey>(); @@ -1307,4 +1209,41 @@ void main() { expect(tester.takeException(), isNull); }); + + // Regression test for https://github.com/flutter/flutter/issues/106659. + testWidgets('Error visual logic is delegated to InputDecorator', (WidgetTester tester) async { + final GlobalKey formKey = GlobalKey(); + + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Form( + key: formKey, + child: DropdownButtonFormField( + items: menuItems.map((String value) { + return DropdownMenuItem( + value: value, + child: Text(value), + ); + }).toList(), + onChanged: onChanged, + validator: (String? v) => 'Required', + onTap: () { + formKey.currentState!.validate(); + }, + ), + ), + ), + ), + ); + + await tester.tap(find.byType(InputDecorator)); + await tester.pump(); + + // Check InputDecorator state because DropdownButtonFormField delegates + // visual logic to the InputDecorator. + final InputDecorator inputDecorator = tester.widget(find.byType(InputDecorator)); + expect(inputDecorator.isFocused, true); + expect(inputDecorator.decoration.errorText, 'Required'); + }); } diff --git a/packages/flutter/test/material/dropdown_menu_test.dart b/packages/flutter/test/material/dropdown_menu_test.dart index 1156fe00a86..03f17a99794 100644 --- a/packages/flutter/test/material/dropdown_menu_test.dart +++ b/packages/flutter/test/material/dropdown_menu_test.dart @@ -4,6 +4,7 @@ import 'dart:ui'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; @@ -1516,7 +1517,7 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/issues/152375. - testWidgets('Searching can hightlight entry after keyboard navigation while focused', (WidgetTester tester) async { + testWidgets('Searching can highlight entry after keyboard navigation while focused', (WidgetTester tester) async { final ThemeData themeData = ThemeData(); await tester.pumpWidget(MaterialApp( theme: themeData, @@ -1874,8 +1875,7 @@ void main() { await tester.pumpAndSettle(); expect(menuAnchor.controller!.isOpen, true); - // Simulate `TextInputAction.done` on textfield - await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); await tester.pumpAndSettle(); expect(menuAnchor.controller!.isOpen, false); }); @@ -1915,31 +1915,29 @@ void main() { // Open the menu await tester.tap(find.byType(DropdownMenu)); await tester.pump(); - final bool isMobile = switch (themeData.platform) { TargetPlatform.android || TargetPlatform.iOS || TargetPlatform.fuchsia => true, TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => false, }; - int expectedCount = isMobile ? 0 : 1; + int expectedCount = 1; // Test onSelected on key press await simulateKeyDownEvent(LogicalKeyboardKey.arrowDown); await tester.pumpAndSettle(); - await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); await tester.pumpAndSettle(); expect(selectionCount, expectedCount); - // The desktop platform closed the menu when a completion action is pressed. So we need to reopen it. - if (!isMobile) { - await tester.tap(find.byType(DropdownMenu)); - await tester.pump(); - } + + // Open the menu + await tester.tap(find.byType(DropdownMenu)); + await tester.pump(); // Disabled item doesn't trigger onSelected callback. final Finder item1 = findMenuItemButton('Item 1'); await tester.tap(item1); await tester.pumpAndSettle(); - expect(controller.text, isMobile ? '' : 'Item 0'); + expect(controller.text, 'Item 0'); expect(selectionCount, expectedCount); final Finder item2 = findMenuItemButton('Item 2'); @@ -3366,47 +3364,6 @@ void main() { expect(controller.offset, 0.0); }); - // Regression test for https://github.com/flutter/flutter/issues/149037. - testWidgets('Dropdown menu follows the text field when keyboard opens', (WidgetTester tester) async { - Widget boilerplate(double bottomInsets) { - return MaterialApp( - home: MediaQuery( - data: MediaQueryData(viewInsets: EdgeInsets.only(bottom: bottomInsets)), - child: Scaffold( - body: Center( - child: DropdownMenu(dropdownMenuEntries: menuChildren), - ), - ), - ), - ); - } - - // Build once without bottom insets and open the menu. - await tester.pumpWidget(boilerplate(0.0)); - await tester.tap(find.byType(TextField).first); - await tester.pump(); - - Finder findMenuPanels() { - return find.byWidgetPredicate((Widget widget) => widget.runtimeType.toString() == '_MenuPanel'); - } - - // Menu vertical position is just under the text field. - expect( - tester.getRect(findMenuPanels()).top, - tester.getRect(find.byType(TextField).first).bottom, - ); - - // Simulate the keyboard opening resizing the view. - await tester.pumpWidget(boilerplate(100.0)); - await tester.pump(); - - // Menu vertical position is just under the text field. - expect( - tester.getRect(findMenuPanels()).top, - tester.getRect(find.byType(TextField).first).bottom, - ); - }); - testWidgets('DropdownMenu with expandedInsets can be aligned', (WidgetTester tester) async { Widget buildMenuAnchor({ AlignmentGeometry alignment = Alignment.topCenter }) { return MaterialApp( @@ -3529,6 +3486,182 @@ void main() { // None of the menus should be closed. expect(dropdownMenuAnchor.controller!.isOpen, true); }); + + group('The menu is attached at the bottom of the TextField', () { + // Define the expected text field bottom instead of querying it using + // tester.getRect because when tight constraints are applied to the + // Dropdown the TextField bounds are expanded while the visible size + // remains 56 pixels. + const double textFieldBottom = 56.0; + + testWidgets('when given loose constraints and expandedInsets is set', (WidgetTester tester) async { + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: DropdownMenu( + expandedInsets: EdgeInsets.zero, + initialSelection: TestMenu.mainMenu3, + dropdownMenuEntries: menuChildrenWithIcons, + ), + ), + )); + + // Open the menu. + await tester.tap(find.byType(TextField)); + await tester.pump(); + + expect(tester.getRect(findMenuMaterial()).top, textFieldBottom); + }); + + testWidgets('when given tight constraints and expandedInsets is set', (WidgetTester tester) async { + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: SizedBox( + width: 200, + height: 300, + child: DropdownMenu( + expandedInsets: EdgeInsets.zero, + initialSelection: TestMenu.mainMenu3, + dropdownMenuEntries: menuChildrenWithIcons, + ), + ), + ), + )); + + // Open the menu. + await tester.tap(find.byType(TextField)); + await tester.pump(); + + expect(tester.getRect(findMenuMaterial()).top, textFieldBottom); + }); + + // Regression test for https://github.com/flutter/flutter/issues/147076. + testWidgets('when given loose constraints and expandedInsets is not set', (WidgetTester tester) async { + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: DropdownMenu( + initialSelection: TestMenu.mainMenu3, + dropdownMenuEntries: menuChildrenWithIcons, + ), + ), + )); + + // Open the menu. + await tester.tap(find.byType(TextField)); + await tester.pump(); + + expect(tester.getRect(findMenuMaterial()).top, textFieldBottom); + }); + + // Regression test for https://github.com/flutter/flutter/issues/147076. + testWidgets('when given tight constraints and expandedInsets is not set', (WidgetTester tester) async { + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: SizedBox( + width: 200, + height: 300, + child: DropdownMenu( + initialSelection: TestMenu.mainMenu3, + dropdownMenuEntries: menuChildrenWithIcons, + ), + ), + ), + )); + + // Open the menu. + await tester.tap(find.byType(TextField)); + await tester.pump(); + + expect(tester.getRect(findMenuMaterial()).top, textFieldBottom); + }); + }); + + // Regression test for https://github.com/flutter/flutter/issues/143505. + testWidgets('Using keyboard navigation to select', (WidgetTester tester) async { + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); + TestMenu? selectedMenu; + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Center( + child: DropdownMenu( + focusNode: focusNode, + dropdownMenuEntries: menuChildren, + onSelected: (TestMenu? menu) { + selectedMenu = menu; + }, + ), + ), + ), + ), + ); + // Pressing the tab key 3 times moves the focus to the icon button. + for (int i = 0; i < 3; i++) { + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pump(); + } + + // Now the focus is on the icon button. + final Element iconButton = tester.firstElement(find.byIcon(Icons.arrow_drop_down)); + expect(Focus.of(iconButton).hasPrimaryFocus, isTrue); + + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(); + + expect(selectedMenu, TestMenu.mainMenu0); + }, variant: TargetPlatformVariant.all()); + + // Regression test for https://github.com/flutter/flutter/issues/143505. + testWidgets('Using keyboard navigation to select and without setting the FocusNode parameter', + (WidgetTester tester) async { + TestMenu? selectedMenu; + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Center( + child: DropdownMenu( + dropdownMenuEntries: menuChildren, + onSelected: (TestMenu? menu) { + selectedMenu = menu; + }, + ), + ), + ), + ), + ); + // If there is no `FocusNode`, by default, `TextField` can receive focus + // on desktop platforms, but not on mobile platforms. Therefore, on desktop + // platforms, it takes 3 tabs to reach the icon button. + final int tabCount = switch (defaultTargetPlatform) { + TargetPlatform.iOS || TargetPlatform.android || TargetPlatform.fuchsia => 2, + TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => 3, + }; + for (int i = 0; i < tabCount; i++) { + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pump(); + } + + // Now the focus is on the icon button. + final Element iconButton = tester.firstElement(find.byIcon(Icons.arrow_drop_down)); + expect(Focus.of(iconButton).hasPrimaryFocus, isTrue); + + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(); + + expect(selectedMenu, TestMenu.mainMenu0); + }, variant: TargetPlatformVariant.all()); } enum TestMenu { diff --git a/packages/flutter/test/material/dropdown_test.dart b/packages/flutter/test/material/dropdown_test.dart index 97f60069cad..09bf16e6b10 100644 --- a/packages/flutter/test/material/dropdown_test.dart +++ b/packages/flutter/test/material/dropdown_test.dart @@ -2429,6 +2429,13 @@ void main() { expect(tester.getTopLeft(find.text('-item0-')).dx, 8); }); + Finder findInputDecoratorBorderPainter() { + return find.descendant( + of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_BorderContainer'), + matching: find.byWidgetPredicate((Widget w) => w is CustomPaint), + ); + } + testWidgets('DropdownButton can be focused, and has focusColor', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; final UniqueKey buttonKey = UniqueKey(); @@ -2451,14 +2458,136 @@ void main() { final FocusNode focusNode = FocusNode(debugLabel: 'DropdownButtonFormField'); addTearDown(focusNode.dispose); - await tester.pumpWidget(buildFrame(isFormField: true, buttonKey: buttonKey, onChanged: onChanged, focusNode: focusNode, autofocus: true)); - await tester.pumpAndSettle(); // Pump a frame for autofocus to take effect. - expect(focusNode.hasPrimaryFocus, isTrue); - expect(find.byType(Material), paints ..rect(rect: const Rect.fromLTRB(0.0, 268.0, 800.0, 332.0), color: const Color(0x1f000000))); + await tester.pumpWidget(buildFrame( + isFormField: true, + buttonKey: buttonKey, + onChanged: onChanged, + focusNode: focusNode, + autofocus: true, + decoration: const InputDecoration(filled: true), + )); - await tester.pumpWidget(buildFrame(isFormField: true, buttonKey: buttonKey, onChanged: onChanged, focusNode: focusNode, focusColor: const Color(0xff00ff00))); - await tester.pumpAndSettle(); // Pump a frame for autofocus to take effect. - expect(find.byType(Material), paints ..rect(rect: const Rect.fromLTRB(0.0, 268.0, 800.0, 332.0), color: const Color(0x1f00ff00))); + await tester.pump(); // Pump a frame for autofocus to take effect. + expect(focusNode.hasPrimaryFocus, isTrue); + + // Default focus Color from InputDecorator defaults. + final ThemeData theme = Theme.of(tester.element(find.byType(InputDecorator))); + expect(findInputDecoratorBorderPainter(), paints + ..path( + style: PaintingStyle.fill, + color: theme.colorScheme.surfaceContainerHighest, + ), + ); + + // Focus color from Decoration. + await tester.pumpWidget(buildFrame( + isFormField: true, + buttonKey: buttonKey, + onChanged: onChanged, + focusNode: focusNode, + decoration: const InputDecoration( + filled: true, + focusColor: Color(0xff00ffff), + ), + )); + + expect(findInputDecoratorBorderPainter(), paints + ..path( + style: PaintingStyle.fill, + color: const Color(0xff00ffff), + ), + ); + + // Focus color from focusColor property. + await tester.pumpWidget(buildFrame( + isFormField: true, + buttonKey: buttonKey, + onChanged: onChanged, + focusNode: focusNode, + decoration: const InputDecoration( + filled: true, + focusColor: Color(0xff00ffff), + ), + focusColor: const Color(0xff00ff00), + )); + + expect(findInputDecoratorBorderPainter(), paints + ..path( + style: PaintingStyle.fill, + color: const Color(0xff00ff00), + ), + ); + }); + + // Regression test for https://github.com/flutter/flutter/issues/147069. + testWidgets('DropdownButtonFormField can be hovered', (WidgetTester tester) async { + tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; + final UniqueKey buttonKey = UniqueKey(); + + await tester.pumpWidget(buildFrame( + isFormField: true, + buttonKey: buttonKey, + onChanged: onChanged, + )); + await tester.pump(); + + // Check inputDecorator.isHovering value because DropdownButtonFormField + // delegates to the InputDecorator which manages hover overlay. + InputDecorator inputDecorator = tester.widget(find.byType(InputDecorator)); + expect(inputDecorator.isHovering, false); + + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); + await gesture.moveTo(tester.getCenter(find.byKey(buttonKey))); + await tester.pump(); + + inputDecorator = tester.widget(find.byType(InputDecorator)); + expect(inputDecorator.isHovering, true); + }); + + // Regression test for https://github.com/flutter/flutter/issues/151460. + testWidgets('DropdownButtonFormField has hover color', (WidgetTester tester) async { + tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; + final UniqueKey buttonKey = UniqueKey(); + + await tester.pumpWidget(buildFrame( + isFormField: true, + buttonKey: buttonKey, + onChanged: onChanged, + // Setting InputDecoration.filled to true is required to get overlay showing. + decoration: const InputDecoration(filled: true), + )); + await tester.pump(); + + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); + await gesture.moveTo(tester.getCenter(find.byKey(buttonKey))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 15)); // Hover animation. + + // Default hover color. + final ThemeData theme = Theme.of(tester.element(find.byType(InputDecorator))); + expect(findInputDecoratorBorderPainter(), paints + ..path( + style: PaintingStyle.fill, + color: Color.alphaBlend(theme.hoverColor, theme.colorScheme.surfaceContainerHighest), + ), + ); + + // Custom hover color. + const Color hoverColor = Color(0xaa00ff00); + await tester.pumpWidget(buildFrame( + isFormField: true, + buttonKey: buttonKey, + onChanged: onChanged, + decoration: const InputDecoration( + filled: true, + hoverColor: hoverColor), + )); + expect(findInputDecoratorBorderPainter(), paints + ..path( + style: PaintingStyle.fill, + color: Color.alphaBlend(hoverColor, theme.colorScheme.surfaceContainerHighest), + ), + ); }); testWidgets("DropdownButton won't be focused if not enabled", (WidgetTester tester) async { @@ -4023,7 +4152,7 @@ void main() { }); }); - testWidgets('BorderRadius property clips dropdown button and dropdown menu', (WidgetTester tester) async { + testWidgets('BorderRadius property clips dropdown menu', (WidgetTester tester) async { const double radius = 20.0; await tester.pumpWidget( @@ -4047,14 +4176,6 @@ void main() { ), ); - final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); - await gesture.addPointer(); - await gesture.moveTo(tester.getCenter(find.byType(DropdownButtonFormField))); - await tester.pumpAndSettle(); - - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); - expect(inkFeatures, paints..rrect(rrect: RRect.fromLTRBR(0.0, 276.0, 800.0, 324.0, const Radius.circular(radius)))); - await tester.tap(find.text('One')); await tester.pumpAndSettle(); diff --git a/packages/flutter/test/material/elevated_button_test.dart b/packages/flutter/test/material/elevated_button_test.dart index 3523ca5d423..29484d52404 100644 --- a/packages/flutter/test/material/elevated_button_test.dart +++ b/packages/flutter/test/material/elevated_button_test.dart @@ -2295,7 +2295,7 @@ void main() { focusNode.dispose(); }); - testWidgets('Default iconAlignment', (WidgetTester tester) async { + testWidgets('Default ElevatedButton icon alignment', (WidgetTester tester) async { Widget buildWidget({ required TextDirection textDirection }) { return MaterialApp( home: Directionality( @@ -2330,7 +2330,7 @@ void main() { expect(buttonTopRight.dx, iconTopRight.dx + 16.0); // 16.0 - padding between icon and button edge. }); - testWidgets('iconAlignment can be customized', (WidgetTester tester) async { + testWidgets('ElevatedButton icon alignment can be customized', (WidgetTester tester) async { Widget buildWidget({ required TextDirection textDirection, required IconAlignment iconAlignment, @@ -2407,6 +2407,35 @@ void main() { expect(buttonTopLeft.dx, iconTopLeft.dx - 24.0); // 24.0 - padding between icon and button edge. }); + testWidgets('ElevatedButton icon alignment respects ButtonStyle.iconAlignment', (WidgetTester tester) async { + Widget buildButton({ IconAlignment? iconAlignment }) { + return MaterialApp( + home: Center( + child: ElevatedButton.icon( + style: ButtonStyle(iconAlignment: iconAlignment), + onPressed: () {}, + icon: const Icon(Icons.add), + label: const Text('button'), + ), + ), + ); + } + + await tester.pumpWidget(buildButton()); + + final Offset buttonTopLeft = tester.getTopLeft(find.byType(Material).last); + final Offset iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add)); + + expect(buttonTopLeft.dx, iconTopLeft.dx - 16.0); + + await tester.pumpWidget(buildButton(iconAlignment: IconAlignment.end)); + + final Offset buttonTopRight = tester.getTopRight(find.byType(Material).last); + final Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); + + expect(buttonTopRight.dx, iconTopRight.dx + 24.0); + }); + // Regression test for https://github.com/flutter/flutter/issues/154798. testWidgets('ElevatedButton.styleFrom can customize the button icon', (WidgetTester tester) async { const Color iconColor = Color(0xFFF000FF); @@ -2415,15 +2444,18 @@ void main() { Widget buildButton({ bool enabled = true }) { return MaterialApp( home: Material( - child: ElevatedButton.icon( - style: ElevatedButton.styleFrom( - iconColor: iconColor, - iconSize: iconSize, - disabledIconColor: disabledIconColor, + child: Center( + child: ElevatedButton.icon( + style: ElevatedButton.styleFrom( + iconColor: iconColor, + iconSize: iconSize, + iconAlignment: IconAlignment.end, + disabledIconColor: disabledIconColor, + ), + onPressed: enabled ? () {} : null, + icon: const Icon(Icons.add), + label: const Text('Button'), ), - onPressed: enabled ? () {} : null, - icon: const Icon(Icons.add), - label: const Text('Button'), ), ), ); @@ -2437,5 +2469,9 @@ void main() { // Test disabled button. await tester.pumpWidget(buildButton(enabled: false)); expect(iconStyle(tester, Icons.add).color, disabledIconColor); + + final Offset buttonTopRight = tester.getTopRight(find.byType(Material).last); + final Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); + expect(buttonTopRight.dx, iconTopRight.dx + 24.0); }); } diff --git a/packages/flutter/test/material/elevated_button_theme_test.dart b/packages/flutter/test/material/elevated_button_theme_test.dart index 4645c5040dd..33486acf555 100644 --- a/packages/flutter/test/material/elevated_button_theme_test.dart +++ b/packages/flutter/test/material/elevated_button_theme_test.dart @@ -228,7 +228,7 @@ void main() { }); }); - testWidgets('Material 3: Theme shadowColor', (WidgetTester tester) async { + testWidgets('Material3 - ElevatedButton repsects Theme shadowColor', (WidgetTester tester) async { const ColorScheme colorScheme = ColorScheme.light(); const Color shadowColor = Color(0xff000001); const Color overriddenColor = Color(0xff000002); @@ -299,7 +299,7 @@ void main() { expect(material.shadowColor, shadowColor); }); - testWidgets('Material 2: Theme shadowColor', (WidgetTester tester) async { + testWidgets('Material2 - ElevatedButton repsects Theme shadowColor', (WidgetTester tester) async { const ColorScheme colorScheme = ColorScheme.light(); const Color shadowColor = Color(0xff000001); const Color overriddenColor = Color(0xff000002); @@ -368,4 +368,40 @@ void main() { material = tester.widget(buttonMaterialFinder); expect(material.shadowColor, shadowColor); }); + + testWidgets('ElevatedButton.icon respects ElevatedButtonTheme ButtonStyle.iconAlignment', (WidgetTester tester) async { + Widget buildButton({ IconAlignment? iconAlignment }) { + return MaterialApp( + theme: ThemeData( + elevatedButtonTheme: ElevatedButtonThemeData( + style: ButtonStyle(iconAlignment: iconAlignment), + ), + ), + home: Scaffold( + body: Center( + child: ElevatedButton.icon( + onPressed: () {}, + icon: const Icon(Icons.add), + label: const Text('button'), + ), + ), + ), + ); + } + + await tester.pumpWidget(buildButton()); + + final Offset buttonTopLeft = tester.getTopLeft(find.byType(Material).last); + final Offset iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add)); + + expect(buttonTopLeft.dx, iconTopLeft.dx - 16.0); + + await tester.pumpWidget(buildButton(iconAlignment: IconAlignment.end)); + await tester.pumpAndSettle(); + + final Offset buttonTopRight = tester.getTopRight(find.byType(Material).last); + final Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); + + expect(buttonTopRight.dx, iconTopRight.dx + 24.0); + }); } diff --git a/packages/flutter/test/material/filled_button_test.dart b/packages/flutter/test/material/filled_button_test.dart index 6ce01c6941d..d102c6a7a29 100644 --- a/packages/flutter/test/material/filled_button_test.dart +++ b/packages/flutter/test/material/filled_button_test.dart @@ -2408,7 +2408,7 @@ void main() { focusNode.dispose(); }); - testWidgets('Default iconAlignment', (WidgetTester tester) async { + testWidgets('Default FilledButton icon alignment', (WidgetTester tester) async { Widget buildWidget({ required TextDirection textDirection }) { return MaterialApp( home: Directionality( @@ -2443,7 +2443,7 @@ void main() { expect(buttonTopRight.dx, iconTopRight.dx + 16.0); // 16.0 - padding between icon and button edge. }); - testWidgets('iconAlignment can be customized', (WidgetTester tester) async { + testWidgets('FilledButton icon alignment can be customized', (WidgetTester tester) async { Widget buildWidget({ required TextDirection textDirection, required IconAlignment iconAlignment, @@ -2520,6 +2520,64 @@ void main() { expect(buttonTopLeft.dx, iconTopLeft.dx - 24.0); // 24.0 - padding between icon and button edge. }); + testWidgets('FilledButton icon alignment respects ButtonStyle.iconAlignment', (WidgetTester tester) async { + Widget buildButton({ IconAlignment? iconAlignment }) { + return MaterialApp( + home: Center( + child: FilledButton.icon( + style: ButtonStyle(iconAlignment: iconAlignment), + onPressed: () {}, + icon: const Icon(Icons.add), + label: const Text('button'), + ), + ), + ); + } + + await tester.pumpWidget(buildButton()); + + final Offset buttonTopLeft = tester.getTopLeft(find.byType(Material).last); + final Offset iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add)); + + expect(buttonTopLeft.dx, iconTopLeft.dx - 16.0); + + await tester.pumpWidget(buildButton(iconAlignment: IconAlignment.end)); + + final Offset buttonTopRight = tester.getTopRight(find.byType(Material).last); + final Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); + + expect(buttonTopRight.dx, iconTopRight.dx + 24.0); + }); + + testWidgets('FilledButton tonal button icon alignment respects ButtonStyle.iconAlignment', (WidgetTester tester) async { + Widget buildButton({ IconAlignment? iconAlignment }) { + return MaterialApp( + home: Center( + child: FilledButton.tonalIcon( + style: ButtonStyle(iconAlignment: iconAlignment), + onPressed: () {}, + icon: const Icon(Icons.add), + label: const Text('button'), + ), + ), + ); + } + + await tester.pumpWidget(buildButton()); + + final Offset buttonTopLeft = tester.getTopLeft(find.byType(Material).last); + final Offset iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add)); + + expect(buttonTopLeft.dx, iconTopLeft.dx - 16.0); + + await tester.pumpWidget(buildButton(iconAlignment: IconAlignment.end)); + + final Offset buttonTopRight = tester.getTopRight(find.byType(Material).last); + final Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); + + expect(buttonTopRight.dx, iconTopRight.dx + 24.0); + }); + testWidgets('Tonal icon default iconAlignment', (WidgetTester tester) async { Widget buildWidget({ required TextDirection textDirection }) { return MaterialApp( @@ -2645,6 +2703,7 @@ void main() { style: FilledButton.styleFrom( iconColor: iconColor, iconSize: iconSize, + iconAlignment: IconAlignment.end, disabledIconColor: disabledIconColor, ), onPressed: enabled ? () {} : null, @@ -2664,5 +2723,9 @@ void main() { // Test disabled button. await tester.pumpWidget(buildButton(enabled: false)); expect(iconStyle(tester, Icons.add).color, disabledIconColor); + + final Offset buttonTopRight = tester.getTopRight(find.byType(Material).last); + final Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); + expect(buttonTopRight.dx, iconTopRight.dx + 24.0); }); } diff --git a/packages/flutter/test/material/filled_button_theme_test.dart b/packages/flutter/test/material/filled_button_theme_test.dart index e3a5fa5b57e..c46298aae78 100644 --- a/packages/flutter/test/material/filled_button_theme_test.dart +++ b/packages/flutter/test/material/filled_button_theme_test.dart @@ -192,7 +192,7 @@ void main() { }); }); - testWidgets('Theme shadowColor', (WidgetTester tester) async { + testWidgets('FilledButton repsects Theme shadowColor', (WidgetTester tester) async { const ColorScheme colorScheme = ColorScheme.light(); const Color shadowColor = Color(0xff000001); const Color overriddenColor = Color(0xff000002); @@ -256,4 +256,76 @@ void main() { material = tester.widget(buttonMaterialFinder); expect(material.shadowColor, shadowColor); }); + + testWidgets('FilledButton.icon respects FilledButtonTheme ButtonStyle.iconAlignment', (WidgetTester tester) async { + Widget buildButton({ IconAlignment? iconAlignment }) { + return MaterialApp( + theme: ThemeData( + filledButtonTheme: FilledButtonThemeData( + style: ButtonStyle(iconAlignment: iconAlignment), + ), + ), + home: Scaffold( + body: Center( + child: FilledButton.icon( + onPressed: () {}, + icon: const Icon(Icons.add), + label: const Text('button'), + ), + ), + ), + ); + } + + await tester.pumpWidget(buildButton()); + + final Offset buttonTopLeft = tester.getTopLeft(find.byType(Material).last); + final Offset iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add)); + + expect(buttonTopLeft.dx, iconTopLeft.dx - 16.0); + + await tester.pumpWidget(buildButton(iconAlignment: IconAlignment.end)); + await tester.pumpAndSettle(); + + final Offset buttonTopRight = tester.getTopRight(find.byType(Material).last); + final Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); + + expect(buttonTopRight.dx, iconTopRight.dx + 24.0); + }); + + testWidgets('Filled tonal button icon respects FilledButtonTheme ButtonStyle.iconAlignment', (WidgetTester tester) async { + Widget buildButton({ IconAlignment? iconAlignment }) { + return MaterialApp( + theme: ThemeData( + filledButtonTheme: FilledButtonThemeData( + style: ButtonStyle(iconAlignment: iconAlignment), + ), + ), + home: Scaffold( + body: Center( + child: FilledButton.tonalIcon( + onPressed: () {}, + icon: const Icon(Icons.add), + label: const Text('button'), + ), + ), + ), + ); + } + + await tester.pumpWidget(buildButton()); + + final Offset buttonTopLeft = tester.getTopLeft(find.byType(Material).last); + final Offset iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add)); + + expect(buttonTopLeft.dx, iconTopLeft.dx - 16.0); + + await tester.pumpWidget(buildButton(iconAlignment: IconAlignment.end)); + await tester.pumpAndSettle(); + + final Offset buttonTopRight = tester.getTopRight(find.byType(Material).last); + final Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); + + expect(buttonTopRight.dx, iconTopRight.dx + 24.0); + }); } diff --git a/packages/flutter/test/material/filter_chip_test.dart b/packages/flutter/test/material/filter_chip_test.dart index 926e4683b6e..2354ec077f7 100644 --- a/packages/flutter/test/material/filter_chip_test.dart +++ b/packages/flutter/test/material/filter_chip_test.dart @@ -10,6 +10,8 @@ library; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import '../widgets/feedback_tester.dart'; @@ -1324,4 +1326,78 @@ void main() { expect(tester.widget(find.byType(RawChip)).chipAnimationStyle, chipAnimationStyle); }); + + testWidgets('FilterChip mouse cursor behavior', (WidgetTester tester) async { + const SystemMouseCursor customCursor = SystemMouseCursors.grab; + + await tester.pumpWidget(wrapForChip( + child: Center( + child: FilterChip( + mouseCursor: customCursor, + label: const Text('Chip'), + onSelected: (bool value) {}, + ), + ), + )); + + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + await gesture.addPointer(location: const Offset(10, 10)); + await tester.pump(); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.basic, + ); + + final Offset chip = tester.getCenter(find.text('Chip')); + await gesture.moveTo(chip); + await tester.pump(); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + customCursor, + ); + }); + + testWidgets('Mouse cursor resolves in focused/unfocused/disabled states', (WidgetTester tester) async { + tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; + final FocusNode focusNode = FocusNode(debugLabel: 'Chip'); + addTearDown(focusNode.dispose); + + Widget buildChip({ required bool enabled }) { + return wrapForChip( + child: Center( + child: FilterChip( + mouseCursor: const WidgetStateMouseCursor.fromMap( + { + WidgetState.disabled: SystemMouseCursors.forbidden, + WidgetState.focused: SystemMouseCursors.grab, + WidgetState.selected: SystemMouseCursors.click, + WidgetState.any: SystemMouseCursors.basic, + }, + ), + focusNode: focusNode, + label: const Text('Chip'), + onSelected: enabled ? (bool value) {} : null, + ), + ), + ); + } + + // Unfocused case. + await tester.pumpWidget(buildChip(enabled: true)); + final TestGesture gesture1 = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + addTearDown(gesture1.removePointer); + await gesture1.addPointer(location: tester.getCenter(find.text('Chip'))); + await tester.pump(); + await gesture1.moveTo(tester.getCenter(find.text('Chip'))); + expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); + + // Focused case. + focusNode.requestFocus(); + await tester.pump(); + expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.grab); + + // Disabled case. + await tester.pumpWidget(buildChip(enabled: false)); + expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden); + }); } diff --git a/packages/flutter/test/material/flexible_space_bar_test.dart b/packages/flutter/test/material/flexible_space_bar_test.dart index a98f76a57f8..093e63a2d65 100644 --- a/packages/flutter/test/material/flexible_space_bar_test.dart +++ b/packages/flutter/test/material/flexible_space_bar_test.dart @@ -333,7 +333,7 @@ void main() { id: 14, flags: [SemanticsFlag.hasImplicitScrolling], rect: TestSemantics.fullScreen, - actions: [SemanticsAction.scrollUp], + actions: [SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], children: [ TestSemantics( id: 5, @@ -441,7 +441,7 @@ void main() { id: 14, flags: [SemanticsFlag.hasImplicitScrolling], rect: TestSemantics.fullScreen, - actions: [SemanticsAction.scrollUp, SemanticsAction.scrollDown], + actions: [SemanticsAction.scrollUp, SemanticsAction.scrollDown, SemanticsAction.scrollToOffset], children: [ TestSemantics( id: 5, @@ -598,7 +598,7 @@ void main() { id: 14, flags: [SemanticsFlag.hasImplicitScrolling], rect: TestSemantics.fullScreen, - actions: [SemanticsAction.scrollUp], + actions: [SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], children: [ TestSemantics( id: 5, @@ -706,7 +706,7 @@ void main() { id: 14, flags: [SemanticsFlag.hasImplicitScrolling], rect: TestSemantics.fullScreen, - actions: [SemanticsAction.scrollUp, SemanticsAction.scrollDown], + actions: [SemanticsAction.scrollUp, SemanticsAction.scrollDown, SemanticsAction.scrollToOffset], children: [ TestSemantics( id: 5, diff --git a/packages/flutter/test/material/ink_well_test.dart b/packages/flutter/test/material/ink_well_test.dart index 3cc961ccc10..9de987c3548 100644 --- a/packages/flutter/test/material/ink_well_test.dart +++ b/packages/flutter/test/material/ink_well_test.dart @@ -11,6 +11,10 @@ import '../widgets/feedback_tester.dart'; import '../widgets/semantics_tester.dart'; void main() { + RenderObject getInkFeatures(WidgetTester tester) { + return tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + } + testWidgets('InkWell gestures control test', (WidgetTester tester) async { final List log = []; @@ -170,7 +174,7 @@ void main() { await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(SizedBox))); await tester.pumpAndSettle(); - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paints..rect(rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), color: const Color(0xff00ff00))); }); @@ -209,7 +213,7 @@ void main() { await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(SizedBox))); await tester.pumpAndSettle(); - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paints..rect(rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), color: const Color(0xff00ff00))); }); @@ -240,7 +244,7 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paintsExactlyCountTimes(#drawRect, 0)); focusNode.requestFocus(); await tester.pumpAndSettle(); @@ -289,7 +293,7 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paintsExactlyCountTimes(#drawRect, 0)); focusNode.requestFocus(); await tester.pumpAndSettle(); @@ -327,13 +331,101 @@ void main() { )); await tester.pumpAndSettle(); final TestGesture gesture = await tester.startGesture(tester.getRect(find.byType(InkWell)).center); - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paints..rect(rect: const Rect.fromLTRB(0, 0, 100, 100), color: pressedColor.withAlpha(0))); await tester.pumpAndSettle(); // Let the press highlight animation finish. expect(inkFeatures, paints..rect(rect: const Rect.fromLTRB(0, 0, 100, 100), color: pressedColor)); await gesture.up(); }); + group('Ink well overlayColor resolution respects WidgetState.selected', () { + const Color selectedHoveredColor = Color(0xff00ff00); + const Color selectedFocusedColor = Color(0xff0000ff); + const Color selectedPressedColor = Color(0xff00ffff); + const Rect inkRect = Rect.fromLTRB(0, 0, 100, 100); + + Widget boilerplate({ FocusNode? focusNode }) { + final WidgetStatesController statesController = WidgetStatesController({MaterialState.selected}); + addTearDown(statesController.dispose); + + return Material( + child: Directionality( + textDirection: TextDirection.ltr, + child: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 100, + height: 100, + child: InkWell( + splashFactory: NoSplash.splashFactory, + focusNode: focusNode, + statesController: statesController, + overlayColor: WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.selected)) { + if (states.contains(WidgetState.pressed)) { + return selectedPressedColor; + } + if (states.contains(WidgetState.hovered)) { + return selectedHoveredColor; + } + if (states.contains(WidgetState.focused)) { + return selectedFocusedColor; + } + return const Color(0xffbadbad); // Shouldn't happen. + } else { + return Colors.black; + } + }), + onTap: () { }, + ), + ), + ), + ), + ); + } + + testWidgets('when focused', (WidgetTester tester) async { + FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; + final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus'); + addTearDown(focusNode.dispose); + + await tester.pumpWidget(boilerplate(focusNode: focusNode)); + await tester.pumpAndSettle(); + + final RenderObject inkFeatures = getInkFeatures(tester); + expect(inkFeatures, paintsExactlyCountTimes(#drawRect, 0)); + focusNode.requestFocus(); + await tester.pumpAndSettle(); + + expect(inkFeatures, paints..rect(rect: inkRect, color: selectedFocusedColor)); + }); + + testWidgets('when hovered', (WidgetTester tester) async { + await tester.pumpWidget(boilerplate()); + await tester.pumpAndSettle(); + + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); + await gesture.addPointer(); + await gesture.moveTo(tester.getCenter(find.byType(SizedBox))); + await tester.pumpAndSettle(); + + final RenderObject inkFeatures = getInkFeatures(tester); + expect(inkFeatures, paints..rect(rect: inkRect, color: selectedHoveredColor)); + }); + + testWidgets('when pressed', (WidgetTester tester) async { + await tester.pumpWidget(boilerplate()); + await tester.pumpAndSettle(); + + final TestGesture gesture = await tester.startGesture(tester.getRect(find.byType(InkWell)).center); + final RenderObject inkFeatures = getInkFeatures(tester); + expect(inkFeatures, paints..rect(rect: inkRect, color: selectedPressedColor.withAlpha(0))); + await tester.pumpAndSettle(); // Let the press highlight animation finish. + expect(inkFeatures, paints..rect(rect: inkRect, color: selectedPressedColor)); + await gesture.up(); + }); + }); + testWidgets('ink response splashColor matches splashColor parameter', (WidgetTester tester) async { FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTouch; final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus'); @@ -367,7 +459,7 @@ void main() { await tester.pumpAndSettle(); final TestGesture gesture = await tester.startGesture(tester.getRect(find.byType(InkWell)).center); await tester.pump(const Duration(milliseconds: 200)); // unconfirmed splash is well underway - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paints..circle(x: 50, y: 50, color: splashColor)); await gesture.up(); focusNode.dispose(); @@ -417,7 +509,7 @@ void main() { await tester.pumpAndSettle(); final TestGesture gesture = await tester.startGesture(tester.getRect(find.byType(InkWell)).center); await tester.pump(const Duration(milliseconds: 200)); // unconfirmed splash is well underway - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paints..circle(x: 50, y: 50, color: splashColor)); await gesture.up(); focusNode.dispose(); @@ -446,7 +538,7 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 0)); focusNode.requestFocus(); await tester.pumpAndSettle(); @@ -477,7 +569,7 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0)); focusNode.requestFocus(); @@ -513,7 +605,7 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0)); // Hover the ink well. @@ -555,7 +647,7 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 0)); expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0)); @@ -607,7 +699,7 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 0)); expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0)); @@ -660,7 +752,7 @@ testWidgets('InkResponse radius can be updated', (WidgetTester tester) async { } await tester.pumpWidget(boilerplate(10)); await tester.pumpAndSettle(); - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 0)); focusNode.requestFocus(); @@ -701,7 +793,7 @@ testWidgets('InkResponse radius can be updated', (WidgetTester tester) async { await tester.pumpWidget(boilerplate(BoxShape.circle)); await tester.pumpAndSettle(); - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 0)); expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0)); @@ -742,7 +834,7 @@ testWidgets('InkResponse radius can be updated', (WidgetTester tester) async { await tester.pumpWidget(boilerplate(BorderRadius.circular(10))); await tester.pumpAndSettle(); - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0)); focusNode.requestFocus(); @@ -791,7 +883,7 @@ testWidgets('InkResponse radius can be updated', (WidgetTester tester) async { await tester.pumpWidget(boilerplate(BorderRadius.circular(20))); await tester.pumpAndSettle(); - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 0)); focusNode.requestFocus(); @@ -862,7 +954,7 @@ testWidgets('InkResponse radius can be updated', (WidgetTester tester) async { await tester.pumpWidget(boilerplate(BorderRadius.circular(20))); await tester.pumpAndSettle(); - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 0)); final TestGesture gesture = await tester.startGesture(tester.getRect(find.byType(InkWell)).center); @@ -945,7 +1037,7 @@ testWidgets('InkResponse radius can be updated', (WidgetTester tester) async { ), )); await tester.pumpAndSettle(); - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paintsExactlyCountTimes(#drawRect, 0)); focusNode.requestFocus(); await tester.pumpAndSettle(); @@ -2048,7 +2140,7 @@ testWidgets('InkResponse radius can be updated', (WidgetTester tester) async { expect(log, equals(['tap-down', 'double-tap'])); await tester.pumpAndSettle(); - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paintsExactlyCountTimes(#drawRect, 0)); }); @@ -2093,7 +2185,7 @@ testWidgets('InkResponse radius can be updated', (WidgetTester tester) async { expect(log, equals(['tap-down', 'tap-down', 'tap-cancel', 'double-tap'])); await tester.pumpAndSettle(); - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 0)); }); @@ -2171,7 +2263,7 @@ testWidgets('InkResponse radius can be updated', (WidgetTester tester) async { await tester.pumpAndSettle(); await gesture.moveTo(const Offset(10, 10)); // fade out the overlay await tester.pump(); // trigger the fade out animation - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); // Fadeout begins with the MaterialStates.hovered overlay color expect(inkFeatures, paints..rect(rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), color: const Color(0xff00ff00))); // 50ms fadeout is 50% complete, overlay color alpha goes from 0xff to 0x80 @@ -2236,7 +2328,7 @@ testWidgets('InkResponse radius can be updated', (WidgetTester tester) async { await tester.pump(const Duration(milliseconds: 200)); // No splash should be painted. - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); + final RenderObject inkFeatures = getInkFeatures(tester); expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 0)); await gesture.up(); diff --git a/packages/flutter/test/material/input_chip_test.dart b/packages/flutter/test/material/input_chip_test.dart index ea00c019f9b..34c2111724c 100644 --- a/packages/flutter/test/material/input_chip_test.dart +++ b/packages/flutter/test/material/input_chip_test.dart @@ -9,6 +9,8 @@ library; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; /// Adds the basic requirements for a Chip. @@ -617,4 +619,77 @@ void main() { expect(tester.widget(find.byType(RawChip)).chipAnimationStyle, chipAnimationStyle); }); + + testWidgets('InputChip mouse cursor behavior', (WidgetTester tester) async { + const SystemMouseCursor customCursor = SystemMouseCursors.grab; + + await tester.pumpWidget(wrapForChip( + child: const Center( + child: InputChip( + mouseCursor: customCursor, + label: Text('Chip'), + ), + ), + )); + + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + await gesture.addPointer(location: const Offset(10, 10)); + await tester.pump(); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.basic, + ); + + final Offset chip = tester.getCenter(find.text('Chip')); + await gesture.moveTo(chip); + await tester.pump(); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + customCursor, + ); + }); + + testWidgets('Mouse cursor resolves in focused/unfocused/disabled states', (WidgetTester tester) async { + tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; + final FocusNode focusNode = FocusNode(debugLabel: 'Chip'); + addTearDown(focusNode.dispose); + + Widget buildChip({ required bool enabled }) { + return wrapForChip( + child: Center( + child: InputChip( + mouseCursor: const WidgetStateMouseCursor.fromMap( + { + WidgetState.disabled: SystemMouseCursors.forbidden, + WidgetState.focused: SystemMouseCursors.grab, + WidgetState.selected: SystemMouseCursors.click, + WidgetState.any: SystemMouseCursors.basic, + }, + ), + focusNode: focusNode, + label: const Text('Chip'), + onSelected: enabled ? (bool value) {} : null, + ), + ), + ); + } + + // Unfocused case. + await tester.pumpWidget(buildChip(enabled: true)); + final TestGesture gesture1 = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + addTearDown(gesture1.removePointer); + await gesture1.addPointer(location: tester.getCenter(find.text('Chip'))); + await tester.pump(); + await gesture1.moveTo(tester.getCenter(find.text('Chip'))); + expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); + + // Focused case. + focusNode.requestFocus(); + await tester.pump(); + expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.grab); + + // Disabled case. + await tester.pumpWidget(buildChip(enabled: false)); + expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden); + }); } diff --git a/packages/flutter/test/material/input_decorator_test.dart b/packages/flutter/test/material/input_decorator_test.dart index b16089a2e2c..33a9d894b76 100644 --- a/packages/flutter/test/material/input_decorator_test.dart +++ b/packages/flutter/test/material/input_decorator_test.dart @@ -1634,8 +1634,9 @@ void main() { ); }); + // Regression test for https://github.com/flutter/flutter/issues/82321. + // Regression test for https://github.com/flutter/flutter/issues/150109. testWidgets('OutlineBorder starts at the right position when border radius is taller than horizontal content padding', (WidgetTester tester) async { - // This is a regression test for https://github.com/flutter/flutter/issues/82321. Widget buildFrame(TextDirection textDirection) { return MaterialApp( home: Scaffold( @@ -1677,8 +1678,8 @@ void main() { ], // The points just before the label bottom left corner should be part of the border. includes: [ - labelBottomLeftLocalToBorder - const Offset(1, 0), - labelBottomLeftLocalToBorder - const Offset(1, 1), + labelBottomLeftLocalToBorder + const Offset(-1, 0), + labelBottomLeftLocalToBorder + const Offset(-1, -1), ], ) ..restore(), @@ -1687,10 +1688,7 @@ void main() { await tester.pumpWidget(buildFrame(TextDirection.rtl)); borderBox = InputDecorator.containerOf(tester.element(findBorderPainter()))!; // Convert label bottom right offset to border path coordinate system. - Offset labelBottomRightLocalToBorder = borderBox.globalToLocal(getLabelRect(tester).bottomRight); - // TODO(bleroux): determine why the position has to be moved by 2 pixels to the right. - // See https://github.com/flutter/flutter/issues/150109. - labelBottomRightLocalToBorder += const Offset(2, 0); + final Offset labelBottomRightLocalToBorder = borderBox.globalToLocal(getLabelRect(tester).bottomRight); expect(findBorderPainter(), paints ..save() @@ -1702,7 +1700,75 @@ void main() { // The points just after the label bottom right corner should be part of the border. includes: [ labelBottomRightLocalToBorder + const Offset(1, 0), - labelBottomRightLocalToBorder + const Offset(1, 1), + labelBottomRightLocalToBorder + const Offset(1, -1), + ], + ) + ..restore(), + ); + }); + + // Regression test for https://github.com/flutter/flutter/issues/159942. + testWidgets('OutlineBorder does not overlap with the label at the default radius', (WidgetTester tester) async { + Widget buildFrame(TextDirection textDirection) { + return MaterialApp( + home: Scaffold( + body: Container( + padding: const EdgeInsets.all(16.0), + alignment: Alignment.center, + child: Directionality( + textDirection: textDirection, + child: const RepaintBoundary( + child: InputDecorator( + isFocused: true, + decoration: InputDecoration( + labelText: labelText, + border: OutlineInputBorder( + gapPadding: 0.0, + ), + ), + ), + ), + ), + ), + ), + ); + } + + await tester.pumpWidget(buildFrame(TextDirection.ltr)); + Rect labelRect = getLabelRect(tester); + RenderBox borderBox = InputDecorator.containerOf(tester.element(findBorderPainter()))!; + expect(findBorderPainter(), paints + ..save() + ..path( + // The points of the label edge should be part of the border. + includes: [ + borderBox.globalToLocal(labelRect.centerLeft), + borderBox.globalToLocal(labelRect.centerRight), + ], + // The points inside the label should not be part of the border. + excludes: [ + borderBox.globalToLocal(labelRect.centerLeft) + const Offset(1, 0), + borderBox.globalToLocal(labelRect.centerRight) + const Offset(-1, 0), + ], + ) + ..restore(), + ); + + await tester.pumpWidget(buildFrame(TextDirection.rtl)); + labelRect = getLabelRect(tester); + borderBox = InputDecorator.containerOf(tester.element(findBorderPainter()))!; + expect(findBorderPainter(), paints + ..save() + ..path( + // The points of the label edge should be part of the border. + includes: [ + borderBox.globalToLocal(labelRect.centerLeft), + borderBox.globalToLocal(labelRect.centerRight), + ], + // The points inside the label should not be part of the border. + excludes: [ + borderBox.globalToLocal(labelRect.centerLeft) + const Offset(1, 0), + borderBox.globalToLocal(labelRect.centerRight) + const Offset(-1, 0), ], ) ..restore(), diff --git a/packages/flutter/test/material/menu_anchor_test.dart b/packages/flutter/test/material/menu_anchor_test.dart index da35266950c..a04ce7ac6e7 100644 --- a/packages/flutter/test/material/menu_anchor_test.dart +++ b/packages/flutter/test/material/menu_anchor_test.dart @@ -3920,6 +3920,46 @@ void main() { tester.getRect(find.byKey(contentKey)).bottom, ); }); + + testWidgets('Menu is correctly offsetted when a LayerLink is provided and alignmentOffset is set', (WidgetTester tester) async { + final MenuController controller = MenuController(); + final UniqueKey contentKey = UniqueKey(); + const double horizontalOffset = 16.0; + const double verticalOffset = 20.0; + + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: Center( + child: MenuAnchor( + controller: controller, + layerLink: LayerLink(), + alignmentOffset: const Offset(horizontalOffset, verticalOffset), + menuChildren: [ + MenuItemButton( + onPressed: () {}, + child: const Text('Button 1'), + ), + ], + builder: (BuildContext context, MenuController controller, Widget? child) { + return SizedBox(key: contentKey, width: 100, height: 100); + }, + ), + ), + ), + )); + + controller.open(); + await tester.pump(); + + expect( + tester.getRect(findMenuPanels()).top, + tester.getRect(find.byKey(contentKey)).bottom + verticalOffset, + ); + expect( + tester.getRect(findMenuPanels()).left, + tester.getRect(find.byKey(contentKey)).left + horizontalOffset, + ); + }); }); group('LocalizedShortcutLabeler', () { @@ -4648,83 +4688,6 @@ void main() { expect(iconStyle(tester, Icons.add).color, disabledIconColor); }); - // Regression test for https://github.com/flutter/flutter/issues/155034. - testWidgets('Content is shown in the root overlay', (WidgetTester tester) async { - final MenuController controller = MenuController(); - final UniqueKey overlayKey = UniqueKey(); - final UniqueKey menuItemKey = UniqueKey(); - - List ancestorRenderTheaters(RenderObject child) { - final List results = []; - RenderObject? node = child; - while (node != null) { - if (node.runtimeType.toString() == '_RenderTheater') { - results.add(node); - } - final RenderObject? parent = node.parent; - node = parent is RenderObject? parent : null; - } - return results; - } - - late final OverlayEntry overlayEntry; - addTearDown((){ - overlayEntry.remove(); - overlayEntry.dispose(); - }); - - Widget boilerplate() { - return MaterialApp( - home: Overlay( - key: overlayKey, - initialEntries: [ - overlayEntry = OverlayEntry( - builder: (BuildContext context) { - return Scaffold( - body: Center( - child: MenuAnchor( - controller: controller, - menuChildren: [ - MenuItemButton( - key: menuItemKey, - onPressed: () {}, - child: const Text('Item 1'), - ), - ], - ), - ), - ); - } - ), - ], - ), - ); - } - - await tester.pumpWidget(boilerplate()); - expect(find.byKey(menuItemKey), findsNothing); - - // Open the menu. - controller.open(); - await tester.pump(); - expect(find.byKey(menuItemKey), findsOne); - - // Expect two overlays: the root overlay created by MaterialApp and the - // overlay created by the boilerplate code. - expect(find.byType(Overlay), findsNWidgets(2)); - - final Iterable overlays = tester.widgetList(find.byType(Overlay)); - final Overlay nonRootOverlay = tester.widget(find.byKey(overlayKey)); - final Overlay rootOverlay = overlays.firstWhere((Overlay overlay) => overlay != nonRootOverlay); - - // Check that the ancestor _RenderTheater for the menu item is the one - // from the root overlay. - expect( - ancestorRenderTheaters(tester.renderObject(find.byKey(menuItemKey))).single, - tester.renderObject(find.byWidget(rootOverlay)), - ); - }); - // Regression test for https://github.com/flutter/flutter/issues/156572. testWidgets('Unattached MenuController does not throw when calling close', (WidgetTester tester) async { final MenuController controller = MenuController(); @@ -4794,6 +4757,92 @@ void main() { expect(openCount, 1); expect(closeCount, 1); }); + + testWidgets('SubmenuButton.submenuIcon updates default arrow icon', (WidgetTester tester) async { + const IconData disabledIcon = Icons.close; + const IconData hoveredIcon = Icons.bolt; + const IconData focusedIcon = Icons.favorite; + const IconData defaultIcon = Icons.add; + final WidgetStateProperty submenuIcon = WidgetStateProperty.resolveWith( + (Set states) { + if (states.contains(WidgetState.disabled)) { + return const Icon(disabledIcon); + } + if (states.contains(WidgetState.hovered)) { + return const Icon(hoveredIcon); + } + if (states.contains(WidgetState.focused)) { + return const Icon(focusedIcon); + } + return const Icon(defaultIcon); + }); + + Widget buildMenu({ + WidgetStateProperty? icon, + bool enabled = true, + }) { + return MaterialApp( + home: Material( + child: MenuBar( + controller: controller, + children: [ + SubmenuButton( + menuChildren: [ + SubmenuButton( + submenuIcon: icon, + menuChildren: enabled + ? [ + MenuItemButton( + child: Text(TestMenu.mainMenu0.label), + ), + ] + : [], + child: Text(TestMenu.subSubMenu110.label), + ), + ], + child: Text(TestMenu.subMenu00.label), + ), + ], + ), + ), + ); + } + + await tester.pumpWidget(buildMenu()); + await tester.tap(find.text(TestMenu.subMenu00.label)); + await tester.pump(); + + expect(find.byIcon(Icons.arrow_right), findsOneWidget); + + controller.close(); + await tester.pump(); + + await tester.pumpWidget(buildMenu(icon: submenuIcon)); + await tester.tap(find.text(TestMenu.subMenu00.label)); + await tester.pump(); + expect(find.byIcon(defaultIcon), findsOneWidget); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(find.byIcon(focusedIcon), findsOneWidget); + + controller.close(); + await tester.pump(); + + await tester.tap(find.text(TestMenu.subMenu00.label)); + await tester.pump(); + await hoverOver(tester, find.text(TestMenu.subSubMenu110.label)); + await tester.pump(); + expect(find.byIcon(hoveredIcon), findsOneWidget); + + controller.close(); + await tester.pump(); + + await tester.pumpWidget(buildMenu(icon: submenuIcon, enabled: false)); + await tester.tap(find.text(TestMenu.subMenu00.label)); + await tester.pump(); + expect(find.byIcon(disabledIcon), findsOneWidget); + }); } List createTestMenus({ diff --git a/packages/flutter/test/material/menu_theme_test.dart b/packages/flutter/test/material/menu_theme_test.dart index 7a0142e1aaf..772c81e70f0 100644 --- a/packages/flutter/test/material/menu_theme_test.dart +++ b/packages/flutter/test/material/menu_theme_test.dart @@ -2,7 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -46,6 +48,49 @@ void main() { ); } + Future hoverOver(WidgetTester tester, Finder finder) async { + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); + await gesture.moveTo(tester.getCenter(finder)); + await tester.pumpAndSettle(); + return gesture; + } + + test('MenuThemeData defaults', () { + const MenuThemeData menuThemeData = MenuThemeData(); + expect(menuThemeData.style, isNull); + expect(menuThemeData.submenuIcon, isNull); + }); + + testWidgets('Default MenuThemeData debugFillProperties', (WidgetTester tester) async { + final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); + const MenuThemeData().debugFillProperties(builder); + + final List description = builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); + + expect(description, []); + }); + + testWidgets('MenuThemeData debugFillProperties', (WidgetTester tester) async { + final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); + const MenuThemeData( + style: MenuStyle(backgroundColor: WidgetStatePropertyAll(Color(0xfffffff1))), + submenuIcon: WidgetStatePropertyAll(Icon(Icons.add)), + ).debugFillProperties(builder); + + final List description = builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); + + expect(description, equalsIgnoringHashCodes([ + 'style: MenuStyle#c6d29(backgroundColor: WidgetStatePropertyAll(Color(alpha: 1.0000, red: 1.0000, green: 1.0000, blue: 0.9451, colorSpace: ColorSpace.sRGB)))', + 'submenuIcon: WidgetStatePropertyAll(Icon(IconData(U+0E047)))' + ])); + }); + test('MenuThemeData lerp special cases', () { expect(MenuThemeData.lerp(null, null, 0), null); const MenuThemeData data = MenuThemeData(); @@ -198,6 +243,95 @@ void main() { .style; expect(textButtonStyle?.overlayColor?.resolve({MaterialState.hovered}), equals(Colors.blueGrey)); }); + + testWidgets('SubmenuButton.submenuIcon updates default arrow icon', (WidgetTester tester) async { + final MenuController controller = MenuController(); + const IconData disabledIcon = Icons.close_fullscreen; + const IconData hoveredIcon = Icons.ac_unit; + const IconData focusedIcon = Icons.zoom_out; + const IconData defaultIcon = Icons.minimize; + final WidgetStateProperty submenuIcon = WidgetStateProperty.resolveWith( + (Set states) { + if (states.contains(WidgetState.disabled)) { + return const Icon(disabledIcon); + } + if (states.contains(WidgetState.hovered)) { + return const Icon(hoveredIcon); + } + if (states.contains(WidgetState.focused)) { + return const Icon(focusedIcon); + } + return const Icon(defaultIcon); + }); + + Widget buildMenu({ + WidgetStateProperty? icon, + bool enabled = true, + }) { + return MaterialApp( + theme: ThemeData(menuTheme: MenuThemeData(submenuIcon: icon)), + home: Material( + child: MenuBar( + controller: controller, + children: [ + SubmenuButton( + menuChildren: [ + SubmenuButton( + menuChildren: enabled + ? [ + MenuItemButton( + child: Text(TestMenu.mainMenu0.label), + ), + ] + : [], + child: Text(TestMenu.subSubMenu110.label), + ), + ], + child: Text(TestMenu.subMenu00.label), + ), + ], + ), + ), + ); + } + + await tester.pumpWidget(buildMenu()); + await tester.tap(find.text(TestMenu.subMenu00.label)); + await tester.pump(); + + expect(find.byIcon(Icons.arrow_right), findsOneWidget); + + controller.close(); + await tester.pump(); + + await tester.pumpWidget(buildMenu(icon: submenuIcon)); + await tester.pumpAndSettle(); + + await tester.tap(find.text(TestMenu.subMenu00.label)); + await tester.pump(); + expect(find.byIcon(defaultIcon), findsOneWidget); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(find.byIcon(focusedIcon), findsOneWidget); + + controller.close(); + await tester.pump(); + + await tester.tap(find.text(TestMenu.subMenu00.label)); + await tester.pump(); + await hoverOver(tester, find.text(TestMenu.subSubMenu110.label)); + await tester.pump(); + expect(find.byIcon(hoveredIcon), findsOneWidget); + + controller.close(); + await tester.pump(); + + await tester.pumpWidget(buildMenu(icon: submenuIcon, enabled: false)); + await tester.tap(find.text(TestMenu.subMenu00.label)); + await tester.pump(); + expect(find.byIcon(disabledIcon), findsOneWidget); + }); } List createTestMenus({ diff --git a/packages/flutter/test/material/navigation_bar_test.dart b/packages/flutter/test/material/navigation_bar_test.dart index 02f7c6b17a6..5e38014a694 100644 --- a/packages/flutter/test/material/navigation_bar_test.dart +++ b/packages/flutter/test/material/navigation_bar_test.dart @@ -1567,21 +1567,22 @@ void main() { }); testWidgets('NavigationBar.labelPadding overrides NavigationDestination.label padding', (WidgetTester tester) async { + const String selectedText = 'Home'; + const String unselectedText = 'Settings'; const EdgeInsetsGeometry labelPadding = EdgeInsets.all(8); Widget buildNavigationBar({ EdgeInsetsGeometry? labelPadding }) { return MaterialApp( - theme: ThemeData(useMaterial3: false), home: Scaffold( bottomNavigationBar: NavigationBar( labelPadding: labelPadding, destinations: const [ NavigationDestination( icon: Icon(Icons.home), - label: 'Home', + label: selectedText, ), NavigationDestination( icon: Icon(Icons.settings), - label: 'Settings', + label: unselectedText, ), ], onDestinationSelected: (int i) { }, @@ -1591,12 +1592,83 @@ void main() { } await tester.pumpWidget(buildNavigationBar()); - expect(_getLabelPadding(tester, 'Home'), const EdgeInsets.only(top: 4)); - expect(_getLabelPadding(tester, 'Settings'), const EdgeInsets.only(top: 4)); + expect(_getLabelPadding(tester, selectedText), const EdgeInsets.only(top: 4)); + expect(_getLabelPadding(tester, unselectedText), const EdgeInsets.only(top: 4)); await tester.pumpWidget(buildNavigationBar(labelPadding: labelPadding)); - expect(_getLabelPadding(tester, 'Home'), labelPadding); - expect(_getLabelPadding(tester, 'Settings'), labelPadding); + expect(_getLabelPadding(tester, selectedText), labelPadding); + expect(_getLabelPadding(tester, unselectedText), labelPadding); + }); + + testWidgets('NavigationBar.labelTextStyle overrides NavigationDestination.label text style', (WidgetTester tester) async { + const String selectedText = 'Home'; + const String unselectedText = 'Settings'; + const String disabledText = 'Bookmark'; + final ThemeData theme = ThemeData(); + Widget buildNavigationBar({ WidgetStateProperty? labelTextStyle }) { + return MaterialApp( + theme: theme, + home: Scaffold( + bottomNavigationBar: NavigationBar( + labelTextStyle: labelTextStyle, + destinations: const [ + NavigationDestination( + icon: Icon(Icons.home), + label: selectedText, + ), + NavigationDestination( + icon: Icon(Icons.settings), + label: unselectedText, + ), + NavigationDestination( + enabled: false, + icon: Icon(Icons.bookmark), + label: disabledText, + ), + ], + ), + ), + ); + } + + await tester.pumpWidget(buildNavigationBar()); + + // Test selected label text style. + expect(_getLabelStyle(tester, selectedText).fontSize, equals(12.0)); + expect(_getLabelStyle(tester, selectedText).color, equals(theme.colorScheme.onSurface)); + + // Test unselected label text style. + expect(_getLabelStyle(tester, unselectedText).fontSize, equals(12.0)); + expect(_getLabelStyle(tester, unselectedText).color, equals(theme.colorScheme.onSurfaceVariant)); + + // Test disabled label text style. + expect(_getLabelStyle(tester, disabledText).fontSize, equals(12.0)); + expect(_getLabelStyle(tester, disabledText).color, equals(theme.colorScheme.onSurfaceVariant.withOpacity(0.38))); + + const TextStyle selectedTextStyle = TextStyle(fontSize: 15, color: Color(0xFF00FF00)); + const TextStyle unselectedTextStyle = TextStyle(fontSize: 15, color: Color(0xFF0000FF)); + const TextStyle disabledTextStyle = TextStyle(fontSize: 16, color: Color(0xFFFF0000)); + await tester.pumpWidget(buildNavigationBar( + labelTextStyle: const WidgetStateProperty.fromMap( + { + WidgetState.disabled: disabledTextStyle, + WidgetState.selected: selectedTextStyle, + WidgetState.any: unselectedTextStyle, + }, + ), + )); + + // Test selected label text style. + expect(_getLabelStyle(tester, selectedText).fontSize, equals(selectedTextStyle.fontSize)); + expect(_getLabelStyle(tester, selectedText).color, equals(selectedTextStyle.color)); + + // Test unselected label text style. + expect(_getLabelStyle(tester, unselectedText).fontSize, equals(unselectedTextStyle.fontSize)); + expect(_getLabelStyle(tester, unselectedText).color, equals(unselectedTextStyle.color)); + + // Test disabled label text style. + expect(_getLabelStyle(tester, disabledText).fontSize, equals(disabledTextStyle.fontSize)); + expect(_getLabelStyle(tester, disabledText).color, equals(disabledTextStyle.color)); }); } @@ -1651,3 +1723,12 @@ EdgeInsetsGeometry _getLabelPadding(WidgetTester tester, String text) { ).first, ).padding; } + +TextStyle _getLabelStyle(WidgetTester tester, String text) { + return tester.widget( + find.descendant( + of: find.text(text), + matching: find.byType(RichText), + ), + ).text.style!; +} diff --git a/packages/flutter/test/material/navigation_drawer_test.dart b/packages/flutter/test/material/navigation_drawer_test.dart index 494d74dd20f..723986cab5a 100644 --- a/packages/flutter/test/material/navigation_drawer_test.dart +++ b/packages/flutter/test/material/navigation_drawer_test.dart @@ -82,45 +82,66 @@ void main() { expect(_getMaterial(tester).color, equals(color)); }); - testWidgets('NavigationDrawer can update destination background color', - (WidgetTester tester) async { - const Color color = Colors.yellow; - final GlobalKey scaffoldKey = GlobalKey(); - final ThemeData theme = ThemeData(); + testWidgets( + 'NavigationDestinationDrawer background color is customizable', + (WidgetTester tester) async { + const Color color = Colors.yellow; + final GlobalKey scaffoldKey = GlobalKey(); + final ThemeData theme = ThemeData(); - await tester.pumpWidget( - _buildWidget( - scaffoldKey, - NavigationDrawer( - children: [ - Text('Headline', style: theme.textTheme.bodyLarge), - NavigationDrawerDestination( - icon: Icon(Icons.ac_unit, color: theme.iconTheme.color), - label: Text('AC', style: theme.textTheme.bodySmall), - backgroundColor: color, - ), - NavigationDrawerDestination( - icon: Icon(Icons.access_alarm, color: theme.iconTheme.color), - label: Text('Alarm', style: theme.textTheme.bodySmall), - backgroundColor: color, - ), - ], - onDestinationSelected: (int i) {}, + await tester.pumpWidget( + _buildWidget( + scaffoldKey, + NavigationDrawer( + children: [ + Text('Headline', style: theme.textTheme.bodyLarge), + NavigationDrawerDestination( + icon: Icon(Icons.ac_unit, color: theme.iconTheme.color), + label: Text('AC', style: theme.textTheme.bodySmall), + ), + NavigationDrawerDestination( + icon: Icon(Icons.access_alarm, color: theme.iconTheme.color), + label: Text('Alarm', style: theme.textTheme.bodySmall), + backgroundColor: color, + ), + ], + onDestinationSelected: (int i) {}, + ), ), - ), - ); + ); - scaffoldKey.currentState!.openDrawer(); - await tester.pump(const Duration(seconds: 1)); // animation done - final ColoredBox destinationColor = tester.firstWidget( - find.descendant( - of: find.byType(NavigationDrawerDestination), - matching: find.byType(ColoredBox), - ), - ); + Finder findDestinationInk(String label) { + return find.descendant( + of: find.ancestor( + of: find.text(label), + matching: find.byType(NavigationDrawerDestination), + ), + matching: find.byType(Ink), + ); + } - expect(destinationColor.color, equals(color)); - }); + scaffoldKey.currentState!.openDrawer(); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); // Animation done. + + // Destination with no custom background color. + await tester.tap(find.text('AC')); + await tester.pump(); + + expect(findDestinationInk('AC'), findsNothing); + + // Destination with a custom background color. + await tester.tap(find.byIcon(Icons.access_alarm)); + await tester.pump(); + + // A Material is added with the custom color. + expect(findDestinationInk('Alarm'), findsOne); + final BoxDecoration destinationDecoration = tester.firstWidget( + findDestinationInk('Alarm'), + ).decoration! as BoxDecoration; + expect(destinationDecoration.color, color); + }, + ); testWidgets('NavigationDrawer can update elevation', (WidgetTester tester) async { diff --git a/packages/flutter/test/material/outlined_button_test.dart b/packages/flutter/test/material/outlined_button_test.dart index 9fe25e976ba..fcdec126d74 100644 --- a/packages/flutter/test/material/outlined_button_test.dart +++ b/packages/flutter/test/material/outlined_button_test.dart @@ -2471,7 +2471,7 @@ void main() { expect(material.color, backgroundColor); }); - testWidgets('Default iconAlignment', (WidgetTester tester) async { + testWidgets('Default OutlinedButton icon alignment', (WidgetTester tester) async { Widget buildWidget({ required TextDirection textDirection }) { return MaterialApp( home: Directionality( @@ -2506,7 +2506,7 @@ void main() { expect(buttonTopRight.dx, iconTopRight.dx + 16.0); // 16.0 - padding between icon and button edge. }); - testWidgets('iconAlignment can be customized', (WidgetTester tester) async { + testWidgets('OutlinedButton icon alignment can be customized', (WidgetTester tester) async { Widget buildWidget({ required TextDirection textDirection, required IconAlignment iconAlignment, @@ -2583,6 +2583,35 @@ void main() { expect(buttonTopLeft.dx, iconTopLeft.dx - 24.0); // 24.0 - padding between icon and button edge. }); + testWidgets('OutlinedButton icon alignment respects ButtonStyle.iconAlignment', (WidgetTester tester) async { + Widget buildButton({ IconAlignment? iconAlignment }) { + return MaterialApp( + home: Center( + child: OutlinedButton.icon( + style: ButtonStyle(iconAlignment: iconAlignment), + onPressed: () {}, + icon: const Icon(Icons.add), + label: const Text('button'), + ), + ), + ); + } + + await tester.pumpWidget(buildButton()); + + final Offset buttonTopLeft = tester.getTopLeft(find.byType(Material).last); + final Offset iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add)); + + expect(buttonTopLeft.dx, iconTopLeft.dx - 16.0); + + await tester.pumpWidget(buildButton(iconAlignment: IconAlignment.end)); + + final Offset buttonTopRight = tester.getTopRight(find.byType(Material).last); + final Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); + + expect(buttonTopRight.dx, iconTopRight.dx + 24.0); + }); + testWidgets("OutlinedButton.icon response doesn't hover when disabled", (WidgetTester tester) async { FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTouch; final FocusNode focusNode = FocusNode(debugLabel: 'OutlinedButton.icon Focus'); @@ -2763,6 +2792,7 @@ void main() { style: OutlinedButton.styleFrom( iconColor: iconColor, iconSize: iconSize, + iconAlignment: IconAlignment.end, disabledIconColor: disabledIconColor, ), onPressed: enabled ? () {} : null, @@ -2782,5 +2812,9 @@ void main() { // Test disabled button. await tester.pumpWidget(buildButton(enabled: false)); expect(iconStyle(tester, Icons.add).color, disabledIconColor); + + final Offset buttonTopRight = tester.getTopRight(find.byType(Material).last); + final Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); + expect(buttonTopRight.dx, iconTopRight.dx + 24.0); }); } diff --git a/packages/flutter/test/material/outlined_button_theme_test.dart b/packages/flutter/test/material/outlined_button_theme_test.dart index 3d71ca4ceef..3d3b426d70e 100644 --- a/packages/flutter/test/material/outlined_button_theme_test.dart +++ b/packages/flutter/test/material/outlined_button_theme_test.dart @@ -235,7 +235,7 @@ void main() { }); }); - testWidgets('Material3: Theme shadowColor', (WidgetTester tester) async { + testWidgets('Material3 - OutlinedButton repsects Theme shadowColor', (WidgetTester tester) async { const ColorScheme colorScheme = ColorScheme.light(); const Color shadowColor = Color(0xff000001); const Color overriddenColor = Color(0xff000002); @@ -306,7 +306,7 @@ void main() { expect(material.shadowColor, shadowColor); }); - testWidgets('Material2: Theme shadowColor', (WidgetTester tester) async { + testWidgets('Material2 - OutlinedButton repsects Theme shadowColor', (WidgetTester tester) async { const ColorScheme colorScheme = ColorScheme.light(); const Color shadowColor = Color(0xff000001); const Color overriddenColor = Color(0xff000002); @@ -375,4 +375,40 @@ void main() { material = tester.widget(buttonMaterialFinder); expect(material.shadowColor, shadowColor); }); + + testWidgets('OutlinedButton.icon alignment respects OutlinedButtonTheme ButtonStyle.iconAlignment', (WidgetTester tester) async { + Widget buildButton({ IconAlignment? iconAlignment }) { + return MaterialApp( + theme: ThemeData( + outlinedButtonTheme: OutlinedButtonThemeData( + style: ButtonStyle(iconAlignment: iconAlignment), + ), + ), + home: Scaffold( + body: Center( + child: OutlinedButton.icon( + onPressed: () {}, + icon: const Icon(Icons.add), + label: const Text('button'), + ), + ), + ), + ); + } + + await tester.pumpWidget(buildButton()); + + final Offset buttonTopLeft = tester.getTopLeft(find.byType(Material).last); + final Offset iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add)); + + expect(buttonTopLeft.dx, iconTopLeft.dx - 16.0); + + await tester.pumpWidget(buildButton(iconAlignment: IconAlignment.end)); + await tester.pumpAndSettle(); + + final Offset buttonTopRight = tester.getTopRight(find.byType(Material).last); + final Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); + + expect(buttonTopRight.dx, iconTopRight.dx + 24.0); + }); } diff --git a/packages/flutter/test/material/page_test.dart b/packages/flutter/test/material/page_test.dart index 7ae339e8e25..26c3cfefac3 100644 --- a/packages/flutter/test/material/page_test.dart +++ b/packages/flutter/test/material/page_test.dart @@ -656,6 +656,54 @@ void main() { expect(tester.getTopLeft(find.text('Page 2')), Offset.zero); }, variant: const TargetPlatformVariant({ TargetPlatform.iOS, TargetPlatform.macOS })); + testWidgets('test fullscreen routes do not transition previous route', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + initialRoute: '/', + onGenerateRoute: (RouteSettings settings) { + if (settings.name == '/') { + return PageRouteBuilder( + pageBuilder: (BuildContext context, Animation animation, Animation secondaryAnimation) { + return Scaffold( + appBar: AppBar( + title: const Text('Page 1'), + ), + body: Container() + ); + }, + ); + } + return MaterialPageRoute( + builder: (BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Page 2'), + ), + body: Container(), + ); + }, + fullscreenDialog: true, + ); + }, + ), + ); + + expect(find.text('Page 1'), findsOneWidget); + expect(find.text('Page 2'), findsNothing); + + final double pageTitleDX = tester.getTopLeft(find.text('Page 1')).dx; + + tester.state(find.byType(Navigator)).pushNamed('/next'); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + + // Second page transition has started. + expect(find.text('Page 2'), findsOneWidget); + + // First page has not moved. + expect(tester.getTopLeft(find.text('Page 1')).dx, equals(pageTitleDX)); + }, variant: const TargetPlatformVariant({ TargetPlatform.iOS, TargetPlatform.macOS })); + testWidgets('test adaptable transitions switch during execution', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( diff --git a/packages/flutter/test/material/page_transitions_theme_test.dart b/packages/flutter/test/material/page_transitions_theme_test.dart index 2361a327ded..3c96def5f7f 100644 --- a/packages/flutter/test/material/page_transitions_theme_test.dart +++ b/packages/flutter/test/material/page_transitions_theme_test.dart @@ -97,6 +97,217 @@ void main() { expect(findZoomPageTransition(), findsOneWidget); }, variant: TargetPlatformVariant.only(TargetPlatform.android)); + testWidgets('Default background color when FadeForwardsPageTransitionBuilder is used', (WidgetTester tester) async { + final Map routes = { + '/': (BuildContext context) => Material( + child: TextButton( + child: const Text('push'), + onPressed: () { Navigator.of(context).pushNamed('/b'); }, + ), + ), + '/b': (BuildContext context) => const Text('page b'), + }; + + await tester.pumpWidget( + MaterialApp( + theme: ThemeData( + pageTransitionsTheme: const PageTransitionsTheme( + builders: { + TargetPlatform.android: FadeForwardsPageTransitionsBuilder() + } + ), + colorScheme: ThemeData().colorScheme.copyWith(surface: Colors.pink) + ), + routes: routes, + ), + ); + + Finder findFadeForwardsPageTransition() { + return find.descendant( + of: find.byType(MaterialApp), + matching: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_FadeForwardsPageTransition'), + ); + } + expect(findFadeForwardsPageTransition(), findsOneWidget); + + await tester.tap(find.text('push')); + await tester.pump(const Duration(milliseconds: 400)); + + final Finder coloredBoxFinder = find.byType(ColoredBox).last; + expect(coloredBoxFinder, findsOneWidget); + final ColoredBox coloredBox = tester.widget(coloredBoxFinder); + expect(coloredBox.color, Colors.pink); + + await tester.pumpAndSettle(); + expect(find.text('page b'), findsOneWidget); + expect(findFadeForwardsPageTransition(), findsOneWidget); + }, variant: TargetPlatformVariant.only(TargetPlatform.android)); + + testWidgets('Override background color in FadeForwardsPageTransitionBuilder', (WidgetTester tester) async { + final Map routes = { + '/': (BuildContext context) => Material( + child: TextButton( + child: const Text('push'), + onPressed: () { Navigator.of(context).pushNamed('/b'); }, + ), + ), + '/b': (BuildContext context) => const Text('page b'), + }; + + await tester.pumpWidget( + MaterialApp( + theme: ThemeData( + pageTransitionsTheme: const PageTransitionsTheme( + builders: { + TargetPlatform.android: FadeForwardsPageTransitionsBuilder( + backgroundColor: Colors.lightGreen, + ) + } + ), + colorScheme: ThemeData().colorScheme.copyWith(surface: Colors.pink) + ), + routes: routes, + ), + ); + + Finder findFadeForwardsPageTransition() { + return find.descendant( + of: find.byType(MaterialApp), + matching: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_FadeForwardsPageTransition'), + ); + } + expect(findFadeForwardsPageTransition(), findsOneWidget); + + await tester.tap(find.text('push')); + await tester.pump(const Duration(milliseconds: 400)); + + final Finder coloredBoxFinder = find.byType(ColoredBox).last; + expect(coloredBoxFinder, findsOneWidget); + final ColoredBox coloredBox = tester.widget(coloredBoxFinder); + expect(coloredBox.color, Colors.lightGreen); + + await tester.pumpAndSettle(); + expect(find.text('page b'), findsOneWidget); + expect(findFadeForwardsPageTransition(), findsOneWidget); + }, variant: TargetPlatformVariant.only(TargetPlatform.android)); + + testWidgets('FadeForwardsPageTransitionBuilder default duration is 800ms', (WidgetTester tester) async { + final Map routes = { + '/': (BuildContext context) => Material( + child: TextButton( + child: const Text('push'), + onPressed: () { Navigator.of(context).pushNamed('/b'); }, + ), + ), + '/b': (BuildContext context) => const Text('page b'), + }; + + await tester.pumpWidget( + MaterialApp( + theme: ThemeData( + pageTransitionsTheme: const PageTransitionsTheme( + builders: { + TargetPlatform.android: FadeForwardsPageTransitionsBuilder() + } + ), + ), + routes: routes, + ), + ); + + Finder findFadeForwardsPageTransition() { + return find.descendant( + of: find.byType(MaterialApp), + matching: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_FadeForwardsPageTransition'), + ); + } + expect(findFadeForwardsPageTransition(), findsOneWidget); + + await tester.tap(find.text('push')); + await tester.pump(const Duration(milliseconds: 799)); + expect(find.text('page b'), findsNothing); + ColoredBox coloredBox = tester.widget(find.byType(ColoredBox).last); + expect(coloredBox.color, isNot(Colors.transparent)); // Color is not transparent during animation. + + await tester.pump(const Duration(milliseconds: 801)); + expect(find.text('page b'), findsOneWidget); + coloredBox = tester.widget(find.byType(ColoredBox).last); + expect(coloredBox.color, Colors.transparent); // Color is transparent during animation. + }, variant: TargetPlatformVariant.only(TargetPlatform.android)); + + testWidgets('Animation duration changes accordingly when page transition builder changes', (WidgetTester tester) async { + Widget buildApp(PageTransitionsBuilder pageTransitionBuilder) { + return MaterialApp( + theme: ThemeData( + pageTransitionsTheme: PageTransitionsTheme( + builders: { + TargetPlatform.android: pageTransitionBuilder, + } + ) + ), + routes: { + '/': (BuildContext context) => Material( + child: TextButton( + child: const Text('push'), + onPressed: () { Navigator.of(context).pushNamed('/b'); }, + ), + ), + '/b': (BuildContext context) => Material( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + TextButton( + child: const Text('pop'), + onPressed: () { + Navigator.of(context).pop(); + }, + ), + const Text('page b'), + ], + ) + ), + }, + ); + } + + await tester.pumpWidget(buildApp(const FadeForwardsPageTransitionsBuilder())); + + Finder findFadeForwardsPageTransition() { + return find.descendant( + of: find.byType(MaterialApp), + matching: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_FadeForwardsPageTransition'), + ); + } + expect(findFadeForwardsPageTransition(), findsOneWidget); + + await tester.tap(find.text('push')); + await tester.pump(const Duration(milliseconds: 799)); + expect(find.text('page b'), findsNothing); + ColoredBox coloredBox = tester.widget(find.byType(ColoredBox).last); + expect(coloredBox.color, isNot(Colors.transparent)); // The color is not transparent during animation. + + await tester.pump(const Duration(milliseconds: 801)); + expect(find.text('page b'), findsOneWidget); + coloredBox = tester.widget(find.byType(ColoredBox).last); + expect(coloredBox.color, Colors.transparent); // The color is transparent during animation. + + await tester.pumpWidget(buildApp(const FadeUpwardsPageTransitionsBuilder())); + await tester.pumpAndSettle(); + expect(find.descendant( + of: find.byType(MaterialApp), + matching: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_FadeUpwardsPageTransition'), + ), findsOneWidget); + await tester.tap(find.text('pop')); + await tester.pump(const Duration(milliseconds: 299)); + expect(find.text('page b'), findsOneWidget); + expect(find.byType(ColoredBox), findsNothing); // ColoredBox doesn't exist in FadeUpwardsPageTransition. + + await tester.pump(const Duration(milliseconds: 301)); + expect(find.text('page b'), findsNothing); + expect(find.text('push'), findsOneWidget); // The first page + expect(find.byType(ColoredBox), findsNothing); + }, variant: TargetPlatformVariant.only(TargetPlatform.android)); + testWidgets('PageTransitionsTheme override builds a _OpenUpwardsPageTransition', (WidgetTester tester) async { final Map routes = { '/': (BuildContext context) => Material( diff --git a/packages/flutter/test/material/popup_menu_test.dart b/packages/flutter/test/material/popup_menu_test.dart index 3a1a76d5469..bf56f5567ff 100644 --- a/packages/flutter/test/material/popup_menu_test.dart +++ b/packages/flutter/test/material/popup_menu_test.dart @@ -4318,6 +4318,41 @@ void main() { expect(inkWell.borderRadius, borderRadius); }); + testWidgets('PopupMenuButton respects materialTapTargetSize', (WidgetTester tester) async { + const double buttonSize = 10.0; + + + Widget buildPopupMenu({required MaterialTapTargetSize tapTargetSize}) { + return MaterialApp( + home: Scaffold( + body: Center( + child: PopupMenuButton( + style: ButtonStyle(tapTargetSize: tapTargetSize), + itemBuilder: (_) => >[ + const PopupMenuItem( + value: 'value', + child: Text('Item 0'), + ), + ], + child: const SizedBox(height: buttonSize, width: buttonSize), + ), + ), + ), + ); + } + // Popup menu with MaterialTapTargetSize.padded. + await tester.pumpWidget(buildPopupMenu(tapTargetSize: MaterialTapTargetSize.padded)); + await tester.pumpAndSettle(); + + expect(tester.getSize(find.byType(InkWell)), const Size(48.0, 48.0)); + + // Popup menu with MaterialTapTargetSize.shrinkWrap. + await tester.pumpWidget(buildPopupMenu(tapTargetSize: MaterialTapTargetSize.shrinkWrap)); + await tester.pumpAndSettle(); + + expect(tester.getSize(find.byType(InkWell)), const Size(buttonSize, buttonSize)); + }); + testWidgets('If requestFocus is false, the original focus should be preserved upon menu appearance.', (WidgetTester tester) async { final FocusNode fieldFocusNode = FocusNode(); addTearDown(fieldFocusNode.dispose); @@ -4352,6 +4387,54 @@ void main() { await tester.pump(); expect(fieldFocusNode.hasFocus, isTrue); }); + + // Regression test for https://github.com/flutter/flutter/issues/152475 + testWidgets('PopupMenuButton updates position on orientation change', (WidgetTester tester) async { + const Size initialSize = Size(400, 800); + const Size newSize = Size(1024, 768); + + await tester.binding.setSurfaceSize(initialSize); + + final GlobalKey buttonKey = GlobalKey(); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: PopupMenuButton( + key: buttonKey, + itemBuilder: (BuildContext context) => >[ + const PopupMenuItem( + value: 1, + child: Text('Option 1'), + ), + ], + ), + ), + ), + ), + ); + + await tester.tap(find.byType(PopupMenuButton)); + await tester.pumpAndSettle(); + + final Rect initialButtonRect = tester.getRect(find.byKey(buttonKey)); + final Rect initialMenuRect = tester.getRect(find.text('Option 1')); + + await tester.binding.setSurfaceSize(newSize); + await tester.pumpAndSettle(); + + final Rect newButtonRect = tester.getRect(find.byKey(buttonKey)); + final Rect newMenuRect = tester.getRect(find.text('Option 1')); + + expect(newButtonRect, isNot(equals(initialButtonRect))); + + expect(newMenuRect, isNot(equals(initialMenuRect))); + + expect(newMenuRect.topLeft - newButtonRect.topLeft, initialMenuRect.topLeft - initialButtonRect.topLeft); + + await tester.binding.setSurfaceSize(null); + }); } Matcher overlaps(Rect other) => OverlapsMatcher(other); diff --git a/packages/flutter/test/material/progress_indicator_test.dart b/packages/flutter/test/material/progress_indicator_test.dart index e5558b07b33..2ba267f2f3d 100644 --- a/packages/flutter/test/material/progress_indicator_test.dart +++ b/packages/flutter/test/material/progress_indicator_test.dart @@ -1217,11 +1217,10 @@ void main() { expect((wrappedTheme as ProgressIndicatorTheme).data, themeData); }); - testWidgets('default size of CircularProgressIndicator is 36x36 - M3', (WidgetTester tester) async { + testWidgets('Material3 - Default size of CircularProgressIndicator', (WidgetTester tester) async { await tester.pumpWidget( - MaterialApp( - theme: theme.copyWith(useMaterial3: true), - home: const Scaffold( + const MaterialApp( + home: Scaffold( body: Material( child: CircularProgressIndicator(), ), @@ -1232,6 +1231,20 @@ void main() { expect(tester.getSize(find.byType(CircularProgressIndicator)), const Size(36, 36)); }); + testWidgets('Material3 - Default size of CircularProgressIndicator when year2023 is false', (WidgetTester tester) async { + await tester.pumpWidget( + const MaterialApp( + home: Scaffold( + body: Material( + child: CircularProgressIndicator(year2023: false), + ), + ), + ), + ); + + expect(tester.getSize(find.byType(CircularProgressIndicator)), const Size(48, 48)); + }); + testWidgets('RefreshProgressIndicator using fields correctly', (WidgetTester tester) async { Future pumpIndicator(RefreshProgressIndicator indicator) { return tester.pumpWidget(Theme(data: theme, child: indicator)); @@ -1527,6 +1540,8 @@ void main() { rrect: RRect.fromLTRBR(100.0 + customTrackGap, 0.0, 200.0, 4.0, const Radius.circular(2.0)), color: theme.colorScheme.secondaryContainer, ) + // Stop indicator. + ..circle() // Active track. ..rrect( rrect: RRect.fromLTRBR(0.0, 0.0, 100.0, 4.0, const Radius.circular(2.0)), @@ -1544,6 +1559,8 @@ void main() { rrect: RRect.fromLTRBR(0.0, 0.0, 200.0, 4.0, const Radius.circular(2.0)), color: theme.colorScheme.secondaryContainer, ) + // Stop indicator. + ..circle() // Active indicator. ..rrect( rrect: RRect.fromLTRBR(0.0, 0.0, 100.0, 4.0, const Radius.circular(2.0)), @@ -1551,6 +1568,200 @@ void main() { ), ); }); + + testWidgets('Default determinate CircularProgressIndicator when year2023 is false', (WidgetTester tester) async { + const EdgeInsetsGeometry padding = EdgeInsets.all(4.0); + await tester.pumpWidget(MaterialApp( + theme: theme, + home: const Center( + child: CircularProgressIndicator( + year2023: false, + value: 0.5, + ), + ), + )); + + final Size indicatorBoxSize = tester.getSize(find.descendant( + of: find.byType(CircularProgressIndicator), + matching: find.byType(ConstrainedBox), + )); + expect( + tester.getSize(find.byType(CircularProgressIndicator)), + equals(Size( + indicatorBoxSize.width + padding.horizontal, + indicatorBoxSize.height + padding.vertical, + )), + ); + expect( + find.byType(CircularProgressIndicator), + paints + // Track. + ..arc( + rect: const Rect.fromLTRB(2.0, 2.0, 38.0, 38.0), + color: theme.colorScheme.secondaryContainer, + strokeWidth: 4.0, + strokeCap: StrokeCap.round, + style: PaintingStyle.stroke, + ) + // Active indicator. + ..arc( + rect: const Rect.fromLTRB(2.0, 2.0, 38.0, 38.0), + color: theme.colorScheme.primary, + strokeWidth: 4.0, + strokeCap: StrokeCap.round, + style: PaintingStyle.stroke, + ), + ); + await expectLater( + find.byType(CircularProgressIndicator), + matchesGoldenFile('circular_progress_indicator_determinate_year2023_false.png'), + ); + }); + + testWidgets('Default indeterminate CircularProgressIndicator when year2023 is false', (WidgetTester tester) async { + const EdgeInsetsGeometry padding = EdgeInsets.all(4.0); + await tester.pumpWidget(MaterialApp( + theme: theme, + home: const Center(child: CircularProgressIndicator(year2023: false)), + )); + + // Advance the animation. + await tester.pump(const Duration(milliseconds: 200)); + + final Size indicatorBoxSize = tester.getSize(find.descendant( + of: find.byType(CircularProgressIndicator), + matching: find.byType(ConstrainedBox), + )); + expect( + tester.getSize(find.byType(CircularProgressIndicator)), + equals(Size( + indicatorBoxSize.width + padding.horizontal, + indicatorBoxSize.height + padding.vertical, + )), + ); + expect( + find.byType(CircularProgressIndicator), + paints + // Active indicator. + ..arc( + rect: const Rect.fromLTRB(2.0, 2.0, 38.0, 38.0), + color: theme.colorScheme.primary, + strokeWidth: 4.0, + strokeCap: StrokeCap.round, + style: PaintingStyle.stroke, + ), + ); + await expectLater( + find.byType(CircularProgressIndicator), + matchesGoldenFile('circular_progress_indicator_indeterminate_year2023_false.png'), + ); + }); + + testWidgets('CircularProgressIndicator track gap can be adjusted when year2023 is false', (WidgetTester tester) async { + Widget buildIndicator({ double? trackGap }) { + return MaterialApp( + home: Center( + child: CircularProgressIndicator( + year2023: false, + trackGap: trackGap, + value: 0.5, + ), + ), + ); + } + + await tester.pumpWidget(buildIndicator()); + await expectLater( + find.byType(CircularProgressIndicator), + matchesGoldenFile('circular_progress_indicator_default_track_gap_year2023_false.png'), + ); + + await tester.pumpWidget(buildIndicator(trackGap: 12.0)); + await expectLater( + find.byType(CircularProgressIndicator), + matchesGoldenFile('circular_progress_indicator_custom_track_gap_year2023_false.png'), + ); + + await tester.pumpWidget(buildIndicator(trackGap: 0.0)); + await expectLater( + find.byType(CircularProgressIndicator), + matchesGoldenFile('circular_progress_indicator_no_track_gap_year2023_false.png'), + ); + }); + + testWidgets('Can override CircularProgressIndicator stroke cap when year2023 is false', (WidgetTester tester) async { + const StrokeCap strokeCap = StrokeCap.square; + await tester.pumpWidget( + const MaterialApp( + home: Center( + child: CircularProgressIndicator( + year2023: false, + strokeCap: strokeCap, + value: 0.5, + ), + ), + ) + ); + + expect( + find.byType(CircularProgressIndicator), + paints + // Track. + ..arc(strokeCap: strokeCap) + // Active indicator. + ..arc(strokeCap: strokeCap) + ); + await expectLater( + find.byType(CircularProgressIndicator), + matchesGoldenFile('circular_progress_indicator_custom_stroke_cap_year2023_false.png'), + ); + }); + + testWidgets('CircularProgressIndicator.constraints can override default size', (WidgetTester tester) async { + const Size size = Size(64, 64); + await tester.pumpWidget( + MaterialApp( + home: Center( + child: CircularProgressIndicator( + constraints: BoxConstraints( + minWidth: size.width, + minHeight: size.height + ), + value: 0.5, + ), + ), + ) + ); + + expect(tester.getSize(find.byType(CircularProgressIndicator)), equals(size)); + }); + + testWidgets('CircularProgressIndicator padding can be customized', (WidgetTester tester) async { + const EdgeInsetsGeometry padding = EdgeInsets.all(12.0); + await tester.pumpWidget( + const MaterialApp( + home: Center( + child: CircularProgressIndicator( + padding: padding, + year2023: false, + value: 0.5, + ), + ), + ) + ); + + final Size indicatorBoxSize = tester.getSize(find.descendant( + of: find.byType(CircularProgressIndicator), + matching: find.byType(ConstrainedBox), + )); + expect( + tester.getSize(find.byType(CircularProgressIndicator)), + equals(Size( + indicatorBoxSize.width + padding.horizontal, + indicatorBoxSize.height + padding.vertical, + )), + ); + }); } class _RefreshProgressIndicatorGolden extends StatefulWidget { diff --git a/packages/flutter/test/material/progress_indicator_theme_test.dart b/packages/flutter/test/material/progress_indicator_theme_test.dart index 2e74f9beae7..c7990573739 100644 --- a/packages/flutter/test/material/progress_indicator_theme_test.dart +++ b/packages/flutter/test/material/progress_indicator_theme_test.dart @@ -2,7 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// reduced-test-set: +// This file is run as part of a reduced test set in CI on Mac and Windows +// machines. +@Tags(['reduced-test-set']) +library; + import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -17,6 +24,50 @@ void main() { expect(identical(ProgressIndicatorThemeData.lerp(data, data, 0.5), data), true); }); + testWidgets('ProgressIndicatorThemeData implements debugFillProperties', (WidgetTester tester) async { + final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); + const ProgressIndicatorThemeData( + color: Color(0XFF0000F1), + linearTrackColor: Color(0XFF0000F2), + linearMinHeight: 25.0, + circularTrackColor: Color(0XFF0000F3), + refreshBackgroundColor: Color(0XFF0000F4), + borderRadius: BorderRadius.all(Radius.circular(8.0)), + stopIndicatorColor: Color(0XFF0000F5), + stopIndicatorRadius: 10.0, + strokeWidth: 8.0, + strokeAlign: BorderSide.strokeAlignOutside, + strokeCap: StrokeCap.butt, + constraints: BoxConstraints.tightFor(width: 80.0, height: 80.0), + trackGap: 16.0, + circularTrackPadding: EdgeInsets.all(12.0), + year2023: false + ).debugFillProperties(builder); + + final List description = builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); + + expect(description, equalsIgnoringHashCodes([ + 'color: Color(alpha: 1.0000, red: 0.0000, green: 0.0000, blue: 0.9451, colorSpace: ColorSpace.sRGB)', + 'linearTrackColor: Color(alpha: 1.0000, red: 0.0000, green: 0.0000, blue: 0.9490, colorSpace: ColorSpace.sRGB)', + 'linearMinHeight: 25.0', + 'circularTrackColor: Color(alpha: 1.0000, red: 0.0000, green: 0.0000, blue: 0.9529, colorSpace: ColorSpace.sRGB)', + 'refreshBackgroundColor: Color(alpha: 1.0000, red: 0.0000, green: 0.0000, blue: 0.9569, colorSpace: ColorSpace.sRGB)', + 'borderRadius: BorderRadius.circular(8.0)', + 'stopIndicatorColor: Color(alpha: 1.0000, red: 0.0000, green: 0.0000, blue: 0.9608, colorSpace: ColorSpace.sRGB)', + 'stopIndicatorRadius: 10.0', + 'strokeWidth: 8.0', + 'strokeAlign: 1.0', + 'strokeCap: StrokeCap.butt', + 'constraints: BoxConstraints(w=80.0, h=80.0)', + 'trackGap: 16.0', + 'circularTrackPadding: EdgeInsets.all(12.0)', + 'year2023: false', + ])); + }); + testWidgets('Can theme LinearProgressIndicator using ProgressIndicatorTheme', (WidgetTester tester) async { const Color color = Color(0XFF00FF00); const Color linearTrackColor = Color(0XFFFF0000); @@ -62,7 +113,7 @@ void main() { ); }); - testWidgets('Can theme LinearProgressIndicator with year2023 to false', (WidgetTester tester) async { + testWidgets('Can theme LinearProgressIndicator when year2023 to false', (WidgetTester tester) async { const Color color = Color(0XFF00FF00); const Color linearTrackColor = Color(0XFFFF0000); const double linearMinHeight = 25.0; @@ -182,4 +233,308 @@ void main() { ), ); }); + + testWidgets('Can theme CircularProgressIndicator using ProgressIndicatorTheme', (WidgetTester tester) async { + const Color color = Color(0XFFFF0000); + const Color circularTrackColor = Color(0XFF0000FF); + const double strokeWidth = 8.0; + const double strokeAlign = BorderSide.strokeAlignOutside; + const StrokeCap strokeCap = StrokeCap.butt; + const BoxConstraints constraints = BoxConstraints.tightFor(width: 80.0, height: 80.0); + const EdgeInsets padding = EdgeInsets.all(14.0); + final ThemeData theme = ThemeData( + progressIndicatorTheme: const ProgressIndicatorThemeData( + color: color, + circularTrackColor: circularTrackColor, + strokeWidth: strokeWidth, + strokeAlign: strokeAlign, + strokeCap: strokeCap, + constraints: constraints, + circularTrackPadding: padding, + ), + ); + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: const Scaffold( + body: Center( + child: CircularProgressIndicator( + value: 0.5, + ), + ), + ), + ), + ); + + expect( + tester.getSize(find.byType(CircularProgressIndicator)), + equals(Size( + constraints.maxWidth + padding.horizontal, + constraints.maxHeight + padding.vertical, + )), + ); + expect( + find.byType(CircularProgressIndicator), + paints + // Track. + ..arc( + color: circularTrackColor, + strokeWidth: strokeWidth, + strokeCap: strokeCap, + ) + // Active indicator. + ..arc( + color: color, + strokeWidth: strokeWidth, + strokeCap: strokeCap, + ), + ); + await expectLater( + find.byType(CircularProgressIndicator), + matchesGoldenFile('circular_progress_indicator_theme.png'), + ); + }); + + testWidgets('Can theme CircularProgressIndicator when year2023 to false', (WidgetTester tester) async { + const Color color = Color(0XFFFF0000); + const Color circularTrackColor = Color(0XFF0000FF); + const double strokeWidth = 8.0; + const double strokeAlign = BorderSide.strokeAlignOutside; + const StrokeCap strokeCap = StrokeCap.butt; + const BoxConstraints constraints = BoxConstraints.tightFor(width: 80.0, height: 80.0); + const double trackGap = 12.0; + const EdgeInsets padding = EdgeInsets.all(18.0); + final ThemeData theme = ThemeData( + progressIndicatorTheme: const ProgressIndicatorThemeData( + color: color, + circularTrackColor: circularTrackColor, + strokeWidth: strokeWidth, + strokeAlign: strokeAlign, + strokeCap: strokeCap, + constraints: constraints, + trackGap: trackGap, + circularTrackPadding: padding, + ), + ); + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: const Scaffold( + body: Center( + child: CircularProgressIndicator( + year2023: false, + value: 0.5, + ), + ), + ), + ), + ); + + final Size indicatorBoxSize = tester.getSize(find.descendant( + of: find.byType(CircularProgressIndicator), + matching: find.byType(ConstrainedBox), + )); + expect(indicatorBoxSize, constraints.biggest); + expect( + tester.getSize(find.byType(CircularProgressIndicator)), + equals(Size( + indicatorBoxSize.width + padding.horizontal, + indicatorBoxSize.height + padding.vertical, + )), + ); + expect( + find.byType(CircularProgressIndicator), + paints + // Track. + ..arc( + color: circularTrackColor, + strokeWidth: strokeWidth, + strokeCap: strokeCap, + ) + // Active indicator. + ..arc( + color: color, + strokeWidth: strokeWidth, + strokeCap: strokeCap, + ), + ); + await expectLater( + find.byType(CircularProgressIndicator), + matchesGoldenFile('circular_progress_indicator_theme_year2023_false.png'), + ); + }); + + testWidgets('Opt into 2024 CircularProgressIndicator appearance with ProgressIndicatorThemeData.year2023', (WidgetTester tester) async { + final ThemeData theme = ThemeData( + progressIndicatorTheme: const ProgressIndicatorThemeData( + year2023: false, + ), + ); + const EdgeInsetsGeometry padding = EdgeInsets.all(4.0); + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: const Scaffold( + body: Center( + child: CircularProgressIndicator(value: 0.5), + ), + ), + ), + ); + + final Size indicatorBoxSize = tester.getSize(find.descendant( + of: find.byType(CircularProgressIndicator), + matching: find.byType(ConstrainedBox), + )); + expect( + tester.getSize(find.byType(CircularProgressIndicator)), + equals(Size( + indicatorBoxSize.width + padding.horizontal, + indicatorBoxSize.height + padding.vertical, + )), + ); + expect( + find.byType(CircularProgressIndicator), + paints + // Track. + ..arc( + rect: const Rect.fromLTRB(2.0, 2.0, 38.0, 38.0), + color: theme.colorScheme.secondaryContainer, + strokeWidth: 4.0, + strokeCap: StrokeCap.round, + style: PaintingStyle.stroke, + ) + // Active indicator. + ..arc( + rect: const Rect.fromLTRB(2.0, 2.0, 38.0, 38.0), + color: theme.colorScheme.primary, + strokeWidth: 4.0, + strokeCap: StrokeCap.round, + style: PaintingStyle.stroke, + ), + ); + await expectLater( + find.byType(CircularProgressIndicator), + matchesGoldenFile('circular_progress_indicator_theme_opt_into_2024.png'), + ); + }); + + testWidgets('CircularProgressIndicator.year2023 overrides ProgressIndicatorThemeData.year2023', (WidgetTester tester) async { + final ThemeData theme = ThemeData( + progressIndicatorTheme: const ProgressIndicatorThemeData( + year2023: false, + ), + ); + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: const Scaffold( + body: Center( + child: CircularProgressIndicator( + year2023: true, + value: 0.5, + ), + ), + ), + ), + ); + + final Size indicatorBoxSize = tester.getSize(find.descendant( + of: find.byType(CircularProgressIndicator), + matching: find.byType(ConstrainedBox), + )); + expect( + tester.getSize(find.byType(CircularProgressIndicator)), + equals(indicatorBoxSize), + ); + expect( + find.byType(CircularProgressIndicator), + paints + // Active indicator. + ..arc( + rect: const Rect.fromLTRB(-0.0, -0.0, 36.0, 36.0), + color: theme.colorScheme.primary, + strokeWidth: 4.0, + style: PaintingStyle.stroke, + ), + ); + await expectLater( + find.byType(CircularProgressIndicator), + matchesGoldenFile('circular_progress_indicator_theme_opt_into_2024_override.png'), + ); + }); + + testWidgets('Opt into 2024 LinearProgressIndicator appearance with ProgressIndicatorThemeData.year2023', (WidgetTester tester) async { + final ThemeData theme = ThemeData( + progressIndicatorTheme: const ProgressIndicatorThemeData( + year2023: false, + ), + ); + const double defaultTrackGap = 4.0; + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: const Scaffold( + body: SizedBox( + width: 200.0, + child: LinearProgressIndicator(value: 0.5), + ), + ), + ), + ); + + expect( + find.byType(LinearProgressIndicator), + paints + // Track. + ..rrect( + rrect: RRect.fromLTRBR(100.0 + defaultTrackGap, 0.0, 200.0, 4.0, const Radius.circular(2.0)), + color: theme.colorScheme.secondaryContainer, + ) + // Stop indicator. + ..circle(x: 198.0, y: 2.0, radius: 2.0, color: theme.colorScheme.primary) + // Active track. + ..rrect( + rrect: RRect.fromLTRBR(0.0, 0.0, 100.0, 4.0, const Radius.circular(2.0)), + color: theme.colorScheme.primary, + ), + ); + }); + + testWidgets('LinearProgressIndicator.year2023 overrides ProgressIndicatorThemeData.year2023', (WidgetTester tester) async { + final ThemeData theme = ThemeData( + progressIndicatorTheme: const ProgressIndicatorThemeData( + year2023: false, + ), + ); + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: const Scaffold( + body: SizedBox( + width: 200.0, + child: LinearProgressIndicator( + year2023: true, + value: 0.5, + ), + ), + ), + ), + ); + + expect( + find.byType(LinearProgressIndicator), + paints + // Track. + ..rect( + rect: const Rect.fromLTRB(0.0, 0.0, 200.0, 4.0), + color: theme.colorScheme.secondaryContainer, + ) + // Active track. + ..rect( + rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 4.0), + color: theme.colorScheme.primary, + ), + ); + }); } diff --git a/packages/flutter/test/material/range_slider_test.dart b/packages/flutter/test/material/range_slider_test.dart index cc516962c5d..2950dc064ea 100644 --- a/packages/flutter/test/material/range_slider_test.dart +++ b/packages/flutter/test/material/range_slider_test.dart @@ -1113,8 +1113,8 @@ void main() { sliderBox, paints ..rrect(color: sliderTheme.inactiveTrackColor) - ..rect(color: sliderTheme.activeTrackColor) - ..rrect(color: sliderTheme.inactiveTrackColor), + ..rrect(color: sliderTheme.inactiveTrackColor) + ..rrect(color: sliderTheme.activeTrackColor), ); expect( sliderBox, @@ -1142,8 +1142,8 @@ void main() { sliderBox, paints ..rrect(color: sliderTheme.inactiveTrackColor) - ..rect(color: activeColor) - ..rrect(color: sliderTheme.inactiveTrackColor), + ..rrect(color: sliderTheme.inactiveTrackColor) + ..rrect(color: activeColor), ); expect( sliderBox, @@ -1170,8 +1170,8 @@ void main() { sliderBox, paints ..rrect(color: inactiveColor) - ..rect(color: sliderTheme.activeTrackColor) - ..rrect(color: inactiveColor), + ..rrect(color: inactiveColor) + ..rrect(color: sliderTheme.activeTrackColor), ); expect( sliderBox, @@ -1202,8 +1202,8 @@ void main() { sliderBox, paints ..rrect(color: inactiveColor) - ..rect(color: activeColor) - ..rrect(color: inactiveColor), + ..rrect(color: inactiveColor) + ..rrect(color: activeColor), ); expect( sliderBox, @@ -1229,8 +1229,8 @@ void main() { sliderBox, paints ..rrect(color: sliderTheme.inactiveTrackColor) - ..rect(color: sliderTheme.activeTrackColor) - ..rrect(color: sliderTheme.inactiveTrackColor), + ..rrect(color: sliderTheme.inactiveTrackColor) + ..rrect(color: sliderTheme.activeTrackColor), ); expect( sliderBox, @@ -1267,8 +1267,8 @@ void main() { sliderBox, paints ..rrect(color: inactiveColor) - ..rect(color: activeColor) - ..rrect(color: inactiveColor), + ..rrect(color: inactiveColor) + ..rrect(color: activeColor), ); expect( sliderBox, @@ -1300,8 +1300,8 @@ void main() { sliderBox, paints ..rrect(color: sliderTheme.disabledInactiveTrackColor) - ..rect(color: sliderTheme.disabledActiveTrackColor) - ..rrect(color: sliderTheme.disabledInactiveTrackColor), + ..rrect(color: sliderTheme.disabledInactiveTrackColor) + ..rrect(color: sliderTheme.disabledActiveTrackColor), ); expect(sliderBox, isNot(paints..circle(color: sliderTheme.thumbColor))); expect(sliderBox, isNot(paints..rect(color: sliderTheme.activeTrackColor))); @@ -1327,8 +1327,8 @@ void main() { sliderBox, paints ..rrect(color: sliderTheme.disabledInactiveTrackColor) - ..rect(color: sliderTheme.disabledActiveTrackColor) - ..rrect(color: sliderTheme.disabledInactiveTrackColor), + ..rrect(color: sliderTheme.disabledInactiveTrackColor) + ..rrect(color: sliderTheme.disabledActiveTrackColor), ); expect(sliderBox, isNot(paints..circle(color: sliderTheme.thumbColor))); expect(sliderBox, isNot(paints..rect(color: sliderTheme.activeTrackColor))); @@ -2080,10 +2080,10 @@ void main() { paints // left inactive track RRect ..rrect(rrect: RRect.fromLTRBAndCorners(-24.0, 3.0, -12.0, 7.0, topLeft: const Radius.circular(2.0), bottomLeft: const Radius.circular(2.0))) - // active track RRect - ..rect(rect: const Rect.fromLTRB(-12.0, 2.0, 0.0, 8.0)) // right inactive track RRect ..rrect(rrect: RRect.fromLTRBAndCorners(0.0, 3.0, 24.0, 7.0, topRight: const Radius.circular(2.0), bottomRight: const Radius.circular(2.0))) + // active track RRect + ..rrect(rrect: RRect.fromLTRBR(-14.0, 2.0, 2.0, 8.0, const Radius.circular(2.0))) // thumbs ..circle(x: -12.0, y: 5.0, radius: 10.0) ..circle(x: 0.0, y: 5.0, radius: 10.0), @@ -2161,22 +2161,41 @@ void main() { await tester.pumpWidget(buildFrame(15)); await tester.pumpAndSettle(); // Finish the animation. - late Rect activeTrackRect; - expect(renderObject, paints..something((Symbol method, List arguments) { - if (method != #drawRect) { + late RRect activeTrackRRect; + expect(renderObject, paints + ..rrect() + ..rrect() + ..something((Symbol method, List arguments) { + if (method != #drawRRect) { return false; } - activeTrackRect = arguments[0] as Rect; + activeTrackRRect = arguments[0] as RRect; return true; })); + const double padding = 4.0; // The 1st thumb should at one-third(5 / 15) of the Slider. // The 2nd thumb should at (8 / 15) of the Slider. // The left of the active track shape is the position of the 1st thumb. // The right of the active track shape is the position of the 2nd thumb. - // 24.0 is the default margin, (800.0 - 24.0 - 24.0) is the slider's width. - expect(nearEqual(activeTrackRect.left, (800.0 - 24.0 - 24.0) * (5 / 15) + 24.0, 0.01), true); - expect(nearEqual(activeTrackRect.right, (800.0 - 24.0 - 24.0) * (8 / 15) + 24.0, 0.01), true); + // 24.0 is the default margin, (800.0 - 24.0 - 24.0 - padding) is the slider's width. + // Where the padding value equals to the track height. + expect( + nearEqual( + activeTrackRRect.left, + (800.0 - 24.0 - 24.0 - padding) * (5 / 15) + 24.0, + 0.01, + ), + true, + ); + expect( + nearEqual( + activeTrackRRect.right, + (800.0 - 24.0 - 24.0 - padding) * (8 / 15) + 24.0 + padding, + 0.01, + ), + true, + ); }); testWidgets('RangeSlider changes mouse cursor when hovered', (WidgetTester tester) async { diff --git a/packages/flutter/test/material/reorderable_list_test.dart b/packages/flutter/test/material/reorderable_list_test.dart index a15264e9bf1..4d034f10892 100644 --- a/packages/flutter/test/material/reorderable_list_test.dart +++ b/packages/flutter/test/material/reorderable_list_test.dart @@ -1925,6 +1925,46 @@ void main() { expect(offsetForFastScroller / offsetForSlowScroller, fastVelocityScalar / slowVelocityScalar); }); + testWidgets('DragBoundary defines the boundary for ReorderableListView.', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Container( + margin: const EdgeInsets.only(top: 100), + height: 300, + child: DragBoundary( + child: ReorderableListView.builder( + itemBuilder: (BuildContext context, int index) { + return ReorderableDragStartListener( + key: ValueKey(index), + index: index, + child: Text('$index'), + ); + }, + itemCount: 5, + onReorder: (int fromIndex, int toIndex) {}, + ), + ), + ), + ), + ), + ); + TestGesture drag = await tester.startGesture(tester.getCenter(find.text('0'))); + await tester.pump(kLongPressTimeout); + await drag.moveBy(const Offset(0, -400)); + await tester.pumpAndSettle(); + expect(tester.getTopLeft(find.text('0')), const Offset(0, 100)); + await drag.up(); + await tester.pumpAndSettle(); + + drag = await tester.startGesture(tester.getCenter(find.text('0'))); + await tester.pump(kLongPressTimeout); + await drag.moveBy(const Offset(0, 800)); + await tester.pumpAndSettle(); + expect(tester.getBottomLeft(find.text('0')), const Offset(0, 400)); + await drag.up(); + await tester.pumpAndSettle(); + }); } Future longPressDrag(WidgetTester tester, Offset start, Offset end) async { diff --git a/packages/flutter/test/material/search_anchor_test.dart b/packages/flutter/test/material/search_anchor_test.dart index 32dcbb4f51b..b657e1e62a3 100644 --- a/packages/flutter/test/material/search_anchor_test.dart +++ b/packages/flutter/test/material/search_anchor_test.dart @@ -1188,9 +1188,9 @@ void main() { await tester.pumpWidget(buildSearchAnchor(platform)); await tester.tap(find.byIcon(Icons.search)); await tester.pumpAndSettle(); - final SizedBox sizedBox = tester.widget(find.descendant(of: findViewContent(), matching: find.byType(SizedBox)).first); - expect(sizedBox.width, 800.0); - expect(sizedBox.height, 600.0); + final Size size = tester.getSize(find.descendant(of: findViewContent(), matching: find.byType(ConstrainedBox)).first); + expect(size.width, 800.0); + expect(size.height, 600.0); } for (final TargetPlatform platform in [ TargetPlatform.linux, TargetPlatform.windows ]) { @@ -1198,9 +1198,9 @@ void main() { await tester.pumpWidget(buildSearchAnchor(platform)); await tester.tap(find.byIcon(Icons.search)); await tester.pumpAndSettle(); - final SizedBox sizedBox = tester.widget(find.descendant(of: findViewContent(), matching: find.byType(SizedBox)).first); - expect(sizedBox.width, 360.0); - expect(sizedBox.height, 400.0); + final Size size = tester.getSize(find.descendant(of: findViewContent(), matching: find.byType(ConstrainedBox)).first); + expect(size.width, 360.0); + expect(size.height, 400.0); } }); @@ -1234,9 +1234,9 @@ void main() { await tester.pumpWidget(buildSearchAnchor(platform)); await tester.tap(find.byIcon(Icons.search)); await tester.pumpAndSettle(); - final SizedBox sizedBox = tester.widget(find.descendant(of: findViewContent(), matching: find.byType(SizedBox)).first); - expect(sizedBox.width, 800.0); - expect(sizedBox.height, 600.0); + final Size size = tester.getSize(find.descendant(of: findViewContent(), matching: find.byType(ConstrainedBox)).first); + expect(size.width, 800.0); + expect(size.height, 600.0); } }); @@ -1378,7 +1378,7 @@ void main() { await tester.pumpWidget(Container()); await tester.pumpWidget(buildAnchor(viewBuilder: (Iterable suggestions) - => GridView.count(crossAxisCount: 5, children: suggestions.toList(),) + => GridView.count(crossAxisCount: 5, children: suggestions.toList()) )); await tester.tap(find.widgetWithIcon(IconButton, Icons.search)); await tester.pumpAndSettle(); @@ -1386,6 +1386,36 @@ void main() { expect(find.byType(GridView), findsOneWidget); }); + testWidgets('SearchAnchor.bar respects viewBuilder property', (WidgetTester tester) async { + Widget buildAnchor({ViewBuilder? viewBuilder}) { + return MaterialApp( + home: Material( + child: SearchAnchor.bar( + viewBuilder: viewBuilder, + suggestionsBuilder: (BuildContext context, SearchController controller) { + return []; + }, + ), + ), + ); + } + + await tester.pumpWidget(buildAnchor()); + await tester.tap(find.byIcon(Icons.search)); + await tester.pumpAndSettle(); + // Default is a ListView. + expect(find.byType(ListView), findsOneWidget); + + await tester.pumpWidget(Container()); + await tester.pumpWidget(buildAnchor(viewBuilder: (Iterable suggestions) + => GridView.count(crossAxisCount: 5, children: suggestions.toList()) + )); + await tester.tap(find.byIcon(Icons.search)); + await tester.pumpAndSettle(); + expect(find.byType(ListView), findsNothing); + expect(find.byType(GridView), findsOneWidget); + }); + testWidgets('SearchAnchor respects viewLeading property', (WidgetTester tester) async { Widget buildAnchor({Widget? viewLeading}) { return MaterialApp( @@ -1692,6 +1722,49 @@ void main() { expect(padding.padding, EdgeInsets.zero); }); + testWidgets('SearchAnchor respects shrinkWrap property', (WidgetTester tester) async { + await tester.pumpWidget(MaterialApp( + home: Material( + child: SearchAnchor( + isFullScreen: false, + shrinkWrap: true, + viewConstraints: const BoxConstraints(), + builder: (BuildContext context, SearchController controller) { + return IconButton(icon: const Icon(Icons.search), onPressed: () { + controller.openView(); + },); + }, + suggestionsBuilder: (BuildContext context, SearchController controller) { + return List.generate( + controller.text.length, + (int index) => ListTile(title: Text('Item $index')), + ); + } + ), + ), + )); + + await tester.tap(find.widgetWithIcon(IconButton, Icons.search)); + await tester.pumpAndSettle(); + + final Finder findDivider = find.descendant(of: findViewContent(), matching: find.byType(Divider)); + + // Divider should not be shown if there are no suggestions + expect(findDivider, findsNothing); + + final Finder findMaterial = find.descendant(of: findViewContent(), matching: find.byType(Material)).first; + final Rect materialRectWithoutSuggestions = tester.getRect(findMaterial); + expect(materialRectWithoutSuggestions, equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 56.0))); + + await tester.enterText(find.byType(SearchBar), 'a'); + await tester.pumpAndSettle(); + + expect(findDivider, findsOneWidget); + + final Rect materialRectWithSuggestions = tester.getRect(findMaterial); + expect(materialRectWithSuggestions, equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 113.0))); + }); + testWidgets('SearchAnchor respects dividerColor property', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Material( @@ -1741,9 +1814,9 @@ void main() { await tester.tap(find.widgetWithIcon(IconButton, Icons.search)); await tester.pumpAndSettle(); - final SizedBox sizedBox = tester.widget(find.descendant(of: findViewContent(), matching: find.byType(SizedBox)).first); - expect(sizedBox.width, 280.0); - expect(sizedBox.height, 390.0); + final Size size = tester.getSize(find.descendant(of: findViewContent(), matching: find.byType(ConstrainedBox)).first); + expect(size.width, 280.0); + expect(size.height, 390.0); }); testWidgets('SearchAnchor respects viewBarPadding property', (WidgetTester tester) async { @@ -1802,7 +1875,7 @@ void main() { await tester.tap(find.byIcon(Icons.search)); await tester.pumpAndSettle(); - final Rect searchViewRect = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(SizedBox)).first); + final Rect searchViewRect = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(ConstrainedBox)).first); expect(searchViewRect, equals(const Rect.fromLTRB(388.0, 0.0, 748.0, 400.0))); // Search view top left should be the same as the anchor top left @@ -1839,7 +1912,7 @@ void main() { await tester.tap(find.byIcon(Icons.search)); await tester.pumpAndSettle(); - final Rect searchViewRect = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(SizedBox)).first); + final Rect searchViewRect = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(ConstrainedBox)).first); expect(searchViewRect, equals(const Rect.fromLTRB(52.0, 0.0, 412.0, 400.0))); // Search view top right should be the same as the anchor top right @@ -2049,7 +2122,7 @@ void main() { await tester.tap(find.byIcon(Icons.search)); await tester.pumpAndSettle(); - final Rect searchViewRect = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(SizedBox)).first); + final Rect searchViewRect = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(ConstrainedBox)).first); expect(searchViewRect, equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 400.0))); // Search view has same width with the default anchor(search bar). @@ -2128,7 +2201,7 @@ void main() { await tester.tap(find.byIcon(Icons.search)); await tester.pumpAndSettle(); - final Rect searchViewRect = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(SizedBox)).first); + final Rect searchViewRect = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(ConstrainedBox)).first); expect(searchViewRect, equals(const Rect.fromLTRB(440.0, 200.0, 800.0, 600.0))); }); @@ -2169,7 +2242,7 @@ void main() { await tester.tap(find.byIcon(Icons.search)); await tester.pumpAndSettle(); - final Rect searchViewRect = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(SizedBox)).first); + final Rect searchViewRect = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(ConstrainedBox)).first); expect(searchViewRect, equals(const Rect.fromLTRB(0.0, 200.0, 360.0, 600.0))); }); @@ -2216,7 +2289,7 @@ void main() { await tester.tap(find.byIcon(Icons.search)); await tester.pumpAndSettle(); - final Rect searchViewRect = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(SizedBox)).first); + final Rect searchViewRect = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(ConstrainedBox)).first); expect(searchViewRect, equals(const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0))); // Test RTL text direction. @@ -2231,7 +2304,7 @@ void main() { await tester.tap(find.byIcon(Icons.search)); await tester.pumpAndSettle(); - final Rect searchViewRectRTL = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(SizedBox)).first); + final Rect searchViewRectRTL = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(ConstrainedBox)).first); expect(searchViewRectRTL, equals(const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0))); }); @@ -2394,7 +2467,7 @@ void main() { await tester.tap(find.byIcon(Icons.search)); await tester.pumpAndSettle(); - final Rect searchViewRect = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(SizedBox)).first); + final Rect searchViewRect = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(ConstrainedBox)).first); expect(searchViewRect.topLeft, equals(const Offset(rootSpacing, rootSpacing))); }); @@ -2440,7 +2513,7 @@ void main() { await tester.tap(find.byIcon(Icons.search)); await tester.pumpAndSettle(); - final Rect searchViewRect = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(SizedBox)).first); + final Rect searchViewRect = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(ConstrainedBox)).first); expect(searchViewRect.bottomRight, equals(const Offset(300.0, 300.0))); }); diff --git a/packages/flutter/test/material/search_view_theme_test.dart b/packages/flutter/test/material/search_view_theme_test.dart index 4dfce1e3f2b..1a6ac951892 100644 --- a/packages/flutter/test/material/search_view_theme_test.dart +++ b/packages/flutter/test/material/search_view_theme_test.dart @@ -33,6 +33,7 @@ void main() { expect(themeData.headerHintStyle, null); expect(themeData.padding, null); expect(themeData.barPadding, null); + expect(themeData.shrinkWrap, null); expect(themeData.dividerColor, null); const SearchViewTheme theme = SearchViewTheme(data: SearchViewThemeData(), child: SizedBox()); @@ -47,6 +48,7 @@ void main() { expect(theme.data.headerHintStyle, null); expect(themeData.padding, null); expect(themeData.barPadding, null); + expect(themeData.shrinkWrap, null); expect(theme.data.dividerColor, null); }); @@ -77,6 +79,7 @@ void main() { constraints: BoxConstraints(minWidth: 350, minHeight: 240), padding: EdgeInsets.only(bottom: 32.0), barPadding: EdgeInsets.zero, + shrinkWrap: true, ).debugFillProperties(builder); final List description = builder.properties @@ -95,6 +98,7 @@ void main() { expect(description[8], 'constraints: BoxConstraints(350.0<=w<=Infinity, 240.0<=h<=Infinity)'); expect(description[9], 'padding: EdgeInsets(0.0, 0.0, 0.0, 32.0)'); expect(description[10], 'barPadding: EdgeInsets.zero'); + expect(description[11], 'shrinkWrap: true'); }); group('[Theme, SearchViewTheme, SearchView properties overrides]', () { @@ -196,9 +200,9 @@ void main() { expect(material.surfaceTintColor, surfaceTintColor); expect(material.shape, shape); - final SizedBox sizedBox = tester.widget(find.descendant(of: findViewContent(), matching: find.byType(SizedBox)).first); - expect(sizedBox.width, 250.0); - expect(sizedBox.height, 450.0); + final Size size = tester.getSize(find.descendant(of: findViewContent(), matching: find.byType(ConstrainedBox)).first); + expect(size.width, 250.0); + expect(size.height, 450.0); final Text hintText = tester.widget(find.text('hint text')); expect(hintText.style?.color, headerHintStyle.color); diff --git a/packages/flutter/test/material/slider_test.dart b/packages/flutter/test/material/slider_test.dart index a1be488cbdb..4d3daf3f280 100644 --- a/packages/flutter/test/material/slider_test.dart +++ b/packages/flutter/test/material/slider_test.dart @@ -4687,4 +4687,210 @@ void main() { ), ); }); + + testWidgets('Default Slider when year2023 is false', (WidgetTester tester) async { + debugDisableShadows = false; + try { + final ThemeData theme = ThemeData(); + final ColorScheme colorScheme = theme.colorScheme; + final Color activeTrackColor = colorScheme.primary; + final Color inactiveTrackColor = colorScheme.secondaryContainer; + final Color secondaryActiveTrackColor = colorScheme.primary.withOpacity(0.54); + final Color disabledActiveTrackColor = colorScheme.onSurface.withOpacity(0.38); + final Color disabledInactiveTrackColor = colorScheme.onSurface.withOpacity(0.12); + final Color disabledSecondaryActiveTrackColor = colorScheme.onSurface.withOpacity(0.38); + final Color activeTickMarkColor = colorScheme.onPrimary; + final Color inactiveTickMarkColor = colorScheme.onSecondaryContainer; + final Color disabledActiveTickMarkColor = colorScheme.onInverseSurface; + final Color disabledInactiveTickMarkColor = colorScheme.onSurface; + final Color thumbColor = colorScheme.primary; + final Color disabledThumbColor = colorScheme.onSurface.withOpacity(0.38); + final Color valueIndicatorColor = colorScheme.inverseSurface; + double value = 0.45; + Widget buildApp({ + int? divisions, + bool enabled = true, + }) { + final ValueChanged? onChanged = !enabled + ? null + : (double d) { + value = d; + }; + return MaterialApp( + home: Directionality( + textDirection: TextDirection.ltr, + child: Material( + child: Center( + child: Theme( + data: theme, + child: Slider( + year2023: false, + value: value, + secondaryTrackValue: 0.75, + label: '$value', + divisions: divisions, + onChanged: onChanged, + ), + ), + ), + ), + ), + ); + } + + await tester.pumpWidget(buildApp()); + + final MaterialInkController material = Material.of(tester.element(find.byType(Slider))); + + // Test default track shape. + const Radius trackOuterCornerRadius = Radius.circular(8.0); + const Radius trackInnerCornerRadius = Radius.circular(2.0); + expect( + material, + paints + // Active track. + ..rrect( + rrect: RRect.fromLTRBAndCorners( + 24.0, 292.0, 356.4, 308.0, + topLeft: trackOuterCornerRadius, + topRight: trackInnerCornerRadius, + bottomRight: trackInnerCornerRadius, + bottomLeft: trackOuterCornerRadius, + ), + color: activeTrackColor, + ) + // Inactive track. + ..rrect( + rrect: RRect.fromLTRBAndCorners( + 368.4, 292.0, 776.0, 308.0, + topLeft: trackInnerCornerRadius, + topRight: trackOuterCornerRadius, + bottomRight: trackOuterCornerRadius, + bottomLeft: trackInnerCornerRadius, + ), + color: inactiveTrackColor, + ) + ); + + // Test default colors for enabled slider. + expect(material, paints..circle()..rrect(color: thumbColor)); + expect(material, isNot(paints..circle()..circle(color: disabledThumbColor))); + expect(material, isNot(paints..rrect(color: disabledActiveTrackColor))); + expect(material, isNot(paints..rrect(color: disabledInactiveTrackColor))); + expect(material, isNot(paints..rrect(color: disabledSecondaryActiveTrackColor))); + + // Test defaults colors for discrete slider. + await tester.pumpWidget(buildApp(divisions: 3)); + expect( + material, + paints + ..rrect(color: activeTrackColor) + ..rrect(color: inactiveTrackColor) + ..rrect(color: secondaryActiveTrackColor) + ..circle(color: activeTickMarkColor) + ..circle(color: activeTickMarkColor) + ..circle(color: inactiveTickMarkColor) + ..circle(color: inactiveTickMarkColor) + ); + expect(material, isNot(paints..circle(color: disabledThumbColor))); + expect(material, isNot(paints..rrect(color: disabledActiveTrackColor))); + expect(material, isNot(paints..rrect(color: disabledInactiveTrackColor))); + expect(material, isNot(paints..rrect(color: disabledSecondaryActiveTrackColor))); + + // Test defaults colors for disabled slider. + await tester.pumpWidget(buildApp(enabled: false)); + await tester.pumpAndSettle(); + expect( + material, + paints + ..rrect(color: disabledActiveTrackColor) + ..rrect(color: disabledInactiveTrackColor) + ..rrect(color: disabledSecondaryActiveTrackColor), + ); + expect(material, paints..circle()..rrect(color: disabledThumbColor)); + expect(material, isNot(paints..circle()..rrect(color: thumbColor))); + expect(material, isNot(paints..rrect(color: activeTrackColor))); + expect(material, isNot(paints..rrect(color: inactiveTrackColor))); + expect(material, isNot(paints..rrect(color: secondaryActiveTrackColor))); + + // Test defaults colors for disabled discrete slider. + await tester.pumpWidget(buildApp(divisions: 3, enabled: false)); + expect( + material, + paints + ..rrect(color: disabledActiveTrackColor) + ..rrect(color: disabledInactiveTrackColor) + ..rrect(color: disabledSecondaryActiveTrackColor) + ..circle(color: disabledActiveTickMarkColor) + ..circle(color: disabledActiveTickMarkColor) + ..circle(color: disabledInactiveTickMarkColor) + ..circle(color: disabledInactiveTickMarkColor) + ..rrect(color: disabledThumbColor), + ); + expect(material, isNot(paints..circle()..rrect(color: thumbColor))); + expect(material, isNot(paints..rrect(color: activeTrackColor))); + expect(material, isNot(paints..rrect(color: inactiveTrackColor))); + expect(material, isNot(paints..rrect(color: secondaryActiveTrackColor))); + + await tester.pumpWidget(buildApp(divisions: 3)); + await tester.pumpAndSettle(); + + final Offset center = tester.getCenter(find.byType(Slider)); + final TestGesture gesture = await tester.startGesture(center); + // Wait for value indicator animation to finish. + await tester.pumpAndSettle(); + + final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay)); + expect( + valueIndicatorBox, + paints + ..scale() + ..rrect(color: valueIndicatorColor) + ); + await gesture.up(); + } finally { + debugDisableShadows = true; + } + }); + + testWidgets('Slider value indicator text when year2023 is false', (WidgetTester tester) async { + const double value = 50; + final List log = []; + final LoggingValueIndicatorShape loggingValueIndicatorShape = LoggingValueIndicatorShape(log); + final ThemeData theme = ThemeData( + sliderTheme: SliderThemeData( + valueIndicatorShape: loggingValueIndicatorShape, + ), + ); + + Widget buildSlider() { + return MaterialApp( + theme: theme, + home: Material( + child: Center( + child: Slider( + year2023: false, + max: 100.0, + divisions: 4, + label: '${value.round()}', + value: value, + onChanged: (double newValue) { }, + ), + ), + ), + ); + } + // Normal text + await tester.pumpWidget(buildSlider()); + final Offset center = tester.getCenter(find.byType(Slider)); + final TestGesture gesture = await tester.startGesture(center); + await tester.pumpAndSettle(); + + expect(log.last.toPlainText(), '50'); + expect(log.last.style!.fontSize, 14.0); + expect(log.last.style!.color, theme.colorScheme.onInverseSurface); + + await gesture.up(); + await tester.pumpAndSettle(); + }); } diff --git a/packages/flutter/test/material/slider_theme_test.dart b/packages/flutter/test/material/slider_theme_test.dart index 01a5c65e939..7e5b9022fbb 100644 --- a/packages/flutter/test/material/slider_theme_test.dart +++ b/packages/flutter/test/material/slider_theme_test.dart @@ -63,6 +63,10 @@ void main() { valueIndicatorTextStyle: TextStyle(color: Colors.black), mouseCursor: MaterialStateMouseCursor.clickable, allowedInteraction: SliderInteraction.tapOnly, + padding: EdgeInsets.all(1.0), + thumbSize: WidgetStatePropertyAll(Size(20, 20)), + trackGap: 10.0, + year2023: false, ).debugFillProperties(builder); final List description = builder.properties @@ -100,7 +104,11 @@ void main() { 'showValueIndicator: always', 'valueIndicatorTextStyle: TextStyle(inherit: true, color: ${const Color(0xff000000)})', 'mouseCursor: WidgetStateMouseCursor(clickable)', - 'allowedInteraction: tapOnly' + 'allowedInteraction: tapOnly', + 'padding: EdgeInsets.all(1.0)', + 'thumbSize: WidgetStatePropertyAll(Size(20.0, 20.0))', + 'trackGap: 10.0', + 'year2023: false', ]); }); @@ -1525,8 +1533,6 @@ void main() { topLeft: const Radius.circular(2.0), bottomLeft: const Radius.circular(2.0), )) - // active track RRect Start 10 pixels from left screen. - ..rect(rect:const Rect.fromLTRB(10.0, 297.0, 790.0, 303.0),) // inactive track RRect. Ends 10 pixels from right of screen. ..rrect(rrect: RRect.fromLTRBAndCorners( 790.0, @@ -1536,6 +1542,11 @@ void main() { topRight: const Radius.circular(2.0), bottomRight: const Radius.circular(2.0), )) + // active track RRect Start 10 pixels from left screen. + ..rrect(rrect: RRect.fromLTRBR( + 8.0, 297.0, 792.0, 303.0, + const Radius.circular(2.0)) + ) // The thumb Left. ..circle(x: 10.0, y: 300.0, radius: 10.0) // The thumb Right. @@ -1798,12 +1809,15 @@ void main() { topLeft: const Radius.circular(2.0), bottomLeft: const Radius.circular(2.0), )) - ..rect(rect: const Rect.fromLTRB(24.0, 297.0, 24.0, 303.0)) ..rrect(rrect: RRect.fromLTRBAndCorners( 24.0, 298.0, 776.0, 302.0, topRight: const Radius.circular(2.0), bottomRight: const Radius.circular(2.0), )) + ..rrect(rrect: RRect.fromLTRBR( + 22.0, 297.0, 26.0, 303.0, + const Radius.circular(2.0)), + ) ..circle(x: 24.0, y: 300.0) ..shadow(elevation: 1.0) ..circle(x: 24.0, y: 300.0) @@ -1847,12 +1861,15 @@ void main() { topLeft: const Radius.circular(2.0), bottomLeft: const Radius.circular(2.0), )) - ..rect(rect: const Rect.fromLTRB(24.0, 297.0, 24.0, 303.0)) ..rrect(rrect: RRect.fromLTRBAndCorners( 24.0, 298.0, 776.0, 302.0, topRight: const Radius.circular(2.0), bottomRight: const Radius.circular(2.0), )) + ..rrect(rrect: RRect.fromLTRBR( + 22.0, 297.0, 26.0, 303.0, + const Radius.circular(2)), + ) ..circle(x: 24.0, y: 300.0) ..path(strokeWidth: 1.0 * 2.0, color: Colors.black) ..circle(x: 24.0, y: 300.0) @@ -2546,9 +2563,11 @@ void main() { }); }); - testWidgets('SliderTrackShape isRounded defaults', (WidgetTester tester) async { + testWidgets('Track shape isRounded defaults', (WidgetTester tester) async { expect(const RectangularSliderTrackShape().isRounded, isFalse); expect(const RoundedRectSliderTrackShape().isRounded, isTrue); + expect(const RectangularRangeSliderTrackShape().isRounded, isFalse); + expect(const RoundedRectRangeSliderTrackShape().isRounded, isTrue); }); testWidgets('SliderThemeData.padding can override the default Slider padding', (WidgetTester tester) async { @@ -2640,6 +2659,266 @@ void main() { ); }); + testWidgets('Can customize track gap when year2023 is false', (WidgetTester tester) async { + Widget buildSlider({ double? trackGap }) { + return MaterialApp( + theme: ThemeData( + sliderTheme: SliderThemeData( + trackGap: trackGap, + ), + ), + home: Material( + child: Center( + child: Slider( + year2023: false, + value: 0.5, + onChanged: (double value) { }, + ), + ), + ), + ); + } + + await tester.pumpWidget(buildSlider(trackGap: 0)); + + final MaterialInkController material = Material.of(tester.element(find.byType(Slider))); + + // Test default track shape. + const Radius trackOuterCornerRadius = Radius.circular(8.0); + const Radius trackInnerCornerRadius = Radius.circular(2.0); + expect( + material, + paints + // Active track. + ..rrect( + rrect: RRect.fromLTRBAndCorners( + 24.0, 292.0, 400.0, 308.0, + topLeft: trackOuterCornerRadius, + topRight: trackInnerCornerRadius, + bottomRight: trackInnerCornerRadius, + bottomLeft: trackOuterCornerRadius, + ), + ) + // Inactive track. + ..rrect( + rrect: RRect.fromLTRBAndCorners( + 400.0, 292.0, 776.0, 308.0, + topLeft: trackInnerCornerRadius, + topRight: trackOuterCornerRadius, + bottomRight: trackOuterCornerRadius, + bottomLeft: trackInnerCornerRadius, + ), + ) + ); + + await tester.pumpWidget(buildSlider(trackGap: 10)); + await tester.pumpAndSettle(); + expect( + material, + paints + // Active track. + ..rrect( + rrect: RRect.fromLTRBAndCorners( + 24.0, 292.0, 390.0, 308.0, + topLeft: trackOuterCornerRadius, + topRight: trackInnerCornerRadius, + bottomRight: trackInnerCornerRadius, + bottomLeft: trackOuterCornerRadius, + ), + ) + // Inactive track. + ..rrect( + rrect: RRect.fromLTRBAndCorners( + 410.0, 292.0, 776.0, 308.0, + topLeft: trackInnerCornerRadius, + topRight: trackOuterCornerRadius, + bottomRight: trackOuterCornerRadius, + bottomLeft: trackInnerCornerRadius, + ), + ) + ); + }); + + testWidgets('Can customize thumb size when year2023 is false', (WidgetTester tester) async { + Widget buildSlider({ WidgetStateProperty? thumbSize }) { + return MaterialApp( + theme: ThemeData( + sliderTheme: SliderThemeData( + thumbSize: thumbSize, + ), + ), + home: Material( + child: Center( + child: Slider( + year2023: false, + value: 0.5, + onChanged: (double value) { }, + ), + ), + ), + ); + } + + await tester.pumpWidget(buildSlider(thumbSize: const WidgetStatePropertyAll(Size(20, 20)))); + + final MaterialInkController material = Material.of(tester.element(find.byType(Slider))); + expect( + material, + paints + ..circle() + ..rrect( + rrect: RRect.fromLTRBR( + 390.0, 290.0, 410.0, 310.0, + const Radius.circular(10.0), + ), + )); + + await tester.pumpWidget(buildSlider(thumbSize: const WidgetStateProperty.fromMap( + { + WidgetState.pressed: Size(20, 20), + WidgetState.any: Size(10, 10), + }, + ))); + await tester.pumpAndSettle(); + + expect( + material, + paints + ..circle() + ..rrect( + rrect: RRect.fromLTRBR( + 395.0, 295.0, 405.0, 305.0, + const Radius.circular(5.0), + ), + )); + + + final Offset center = tester.getCenter(find.byType(Slider)); + final TestGesture gesture = await tester.startGesture(center); + await tester.pumpAndSettle(); + + expect( + material, + paints + ..circle() + ..rrect( + rrect: RRect.fromLTRBR( + 390.0, 295.0, 410.0, 305.0, + const Radius.circular(5.0), + ), + )); + + await gesture.up(); + await tester.pumpAndSettle(); + }); + + testWidgets('Opt into 2024 Slider appearance with SliderThemeData.year2023', (WidgetTester tester) async { + final ThemeData theme = ThemeData( + sliderTheme: const SliderThemeData(year2023: false), + ); + final ColorScheme colorScheme = theme.colorScheme; + final Color activeTrackColor = colorScheme.primary; + final Color inactiveTrackColor = colorScheme.secondaryContainer; + const double value = 0.45; + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: Material( + child: Center( + child: Slider( + value: value, + onChanged: (double value) {}, + ), + ), + ), + ), + ); + + final MaterialInkController material = Material.of(tester.element(find.byType(Slider))); + + // Test default track shape. + const Radius trackOuterCornerRadius = Radius.circular(8.0); + const Radius trackInnerCornderRadius = Radius.circular(2.0); + expect( + material, + paints + // Active track. + ..rrect( + rrect: RRect.fromLTRBAndCorners( + 24.0, 292.0, 356.4, 308.0, + topLeft: trackOuterCornerRadius, + topRight: trackInnerCornderRadius, + bottomRight: trackInnerCornderRadius, + bottomLeft: trackOuterCornerRadius, + ), + color: activeTrackColor, + ) + // Inctive track. + ..rrect( + rrect: RRect.fromLTRBAndCorners( + 368.4, 292.0, 776.0, 308.0, + topLeft: trackInnerCornderRadius, + topRight: trackOuterCornerRadius, + bottomRight: trackOuterCornerRadius, + bottomLeft: trackInnerCornderRadius, + ), + color: inactiveTrackColor, + ), + ); + }); + + testWidgets('Slider.year2023 overrides SliderThemeData.year2023', (WidgetTester tester) async { + final ThemeData theme = ThemeData( + sliderTheme: const SliderThemeData(year2023: false), + ); + final ColorScheme colorScheme = theme.colorScheme; + final Color activeTrackColor = colorScheme.primary; + final Color inactiveTrackColor = colorScheme.surfaceContainerHighest; + const double value = 0.45; + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Center( + child: Theme( + data: theme, + child: Slider( + year2023: true, + value: value, + onChanged: (double value) { }, + ), + ), + ), + ), + ), + ); + + final MaterialInkController material = Material.of(tester.element(find.byType(Slider))); + + // Test default track shape. + const Radius activeTrackCornerRadius = Radius.circular(3.0); + const Radius inactiveTrackCornerRadius = Radius.circular(2.0); + expect( + material, + paints + // Active track. + ..rrect( + rrect: RRect.fromLTRBR( + 360.4, 298.0, 776.0, 302.0, + inactiveTrackCornerRadius, + ), + color: inactiveTrackColor, + ) + // Inctive track. + ..rrect( + rrect: RRect.fromLTRBR( + 24.0, 297.0, 364.4, 303.0, + activeTrackCornerRadius, + ), + color: activeTrackColor, + ), + ); + }); + group('Material 2', () { // These tests are only relevant for Material 2. Once Material 2 // support is deprecated and the APIs are removed, these tests @@ -2678,17 +2957,14 @@ void main() { }; return MaterialApp( theme: theme, - home: Directionality( - textDirection: TextDirection.ltr, - child: Material( - child: Center( - child: Slider( - value: value, - secondaryTrackValue: 0.75, - label: '$value', - divisions: divisions, - onChanged: onChanged, - ), + home: Material( + child: Center( + child: Slider( + value: value, + secondaryTrackValue: 0.75, + label: '$value', + divisions: divisions, + onChanged: onChanged, ), ), ), @@ -2810,23 +3086,20 @@ void main() { Widget buildApp(String value, { double sliderValue = 0.5, TextScaler textScaler = TextScaler.noScaling }) { return MaterialApp( theme: theme, - home: Directionality( - textDirection: TextDirection.ltr, - child: MediaQuery( - data: MediaQueryData(textScaler: textScaler), - child: Material( - child: Row( - children: [ - Expanded( - child: Slider( - value: sliderValue, - label: value, - divisions: 3, - onChanged: (double d) { }, - ), + home: MediaQuery( + data: MediaQueryData(textScaler: textScaler), + child: Material( + child: Row( + children: [ + Expanded( + child: Slider( + value: sliderValue, + label: value, + divisions: 3, + onChanged: (double d) { }, ), - ], - ), + ), + ], ), ), ), diff --git a/packages/flutter/test/material/tab_bar_theme_test.dart b/packages/flutter/test/material/tab_bar_theme_test.dart index 5fa8cde6e85..74bb1218594 100644 --- a/packages/flutter/test/material/tab_bar_theme_test.dart +++ b/packages/flutter/test/material/tab_bar_theme_test.dart @@ -1791,4 +1791,58 @@ void main() { targetRect = const Rect.fromLTRB(275.0, 0.0, 325.0, 48.0); expectIndicatorAttrs(tabBarBox, rect: rect, targetRect: targetRect); }); + + testWidgets('TabBar inherits splashBorderRadius from theme', (WidgetTester tester) async { + const Color hoverColor = Color(0xfff44336); + const double radius = 20; + await tester.pumpWidget( + Material( + child: Localizations( + locale: const Locale('en', 'US'), + delegates: const >[ + DefaultMaterialLocalizations.delegate, + DefaultWidgetsLocalizations.delegate, + ], + child: DefaultTabController( + length: 1, + child: TabBarTheme( + data: TabBarThemeData( + splashBorderRadius: BorderRadius.circular(radius), + ), + child: const TabBar( + overlayColor: WidgetStateMapper( + { + WidgetState.hovered: hoverColor, + WidgetState.any: Colors.black54, + }, + ), + tabs: [ + Tab( + child: Text(''), + ), + ], + ), + ), + ), + ), + ), + ); + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + await gesture.moveTo(tester.getCenter(find.byType(Tab))); + await tester.pumpAndSettle(); + final Finder findInkWell = find.byType(InkWell); + + final BuildContext context = tester.element(findInkWell); + expect( + Material.of(context), + paints..rrect( + color: hoverColor, + rrect: RRect.fromRectAndRadius( + tester.getRect(findInkWell), + const Radius.circular(radius), + ), + ), + ); + gesture.removePointer(); + }); } diff --git a/packages/flutter/test/material/tabs_test.dart b/packages/flutter/test/material/tabs_test.dart index 2315483efcf..e51a0146871 100644 --- a/packages/flutter/test/material/tabs_test.dart +++ b/packages/flutter/test/material/tabs_test.dart @@ -2488,7 +2488,7 @@ void main() { expect(tabBarBox.size.height, 48.0); // Ease in sine (accelerating). - double accelerateIntepolation(double fraction) { + double accelerateInterpolation(double fraction) { return 1.0 - math.cos((fraction * math.pi) / 2.0); } @@ -2499,8 +2499,8 @@ void main() { }) { const double indicatorWeight = 3.0; final double tabChangeProgress = (controller.index - controller.animation!.value).abs(); - final double leftFraction = accelerateIntepolation(tabChangeProgress); - final double rightFraction = accelerateIntepolation(tabChangeProgress); + final double leftFraction = accelerateInterpolation(tabChangeProgress); + final double rightFraction = accelerateInterpolation(tabChangeProgress); final RRect rrect = RRect.fromLTRBAndCorners( lerpDouble(rect.left, targetRect.left, leftFraction)!, @@ -3677,7 +3677,7 @@ void main() { const String tab10title = 'This is a very wide tab #10\nTab 11 of 20'; const List hiddenFlags = [SemanticsFlag.isHidden, SemanticsFlag.isFocusable, SemanticsFlag.hasSelectedState]; - expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollLeft])); + expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollLeft, SemanticsAction.scrollToOffset])); expect(semantics, includesNodeWith(label: tab0title)); expect(semantics, includesNodeWith(label: tab10title, flags: hiddenFlags)); @@ -3685,18 +3685,18 @@ void main() { await tester.pumpAndSettle(); expect(semantics, includesNodeWith(label: tab0title, flags: hiddenFlags)); - expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollLeft, SemanticsAction.scrollRight])); + expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollLeft, SemanticsAction.scrollRight, SemanticsAction.scrollToOffset])); expect(semantics, includesNodeWith(label: tab10title)); controller.index = 19; await tester.pumpAndSettle(); - expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollRight])); + expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollRight, SemanticsAction.scrollToOffset])); controller.index = 0; await tester.pumpAndSettle(); - expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollLeft])); + expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollLeft, SemanticsAction.scrollToOffset])); expect(semantics, includesNodeWith(label: tab0title)); expect(semantics, includesNodeWith(label: tab10title, flags: hiddenFlags)); @@ -7313,7 +7313,7 @@ void main() { }); // This is a regression test for https://github.com/flutter/flutter/issues/150316. - testWidgets('Scrollable TabBar wuth transparent divider expands to full width', (WidgetTester tester) async { + testWidgets('Scrollable TabBar with transparent divider expands to full width', (WidgetTester tester) async { Widget buildTabBar({ Color? dividerColor, TabAlignment? tabAlignment }) { return boilerplate( child: Center( @@ -7424,7 +7424,7 @@ void main() { await tester.pumpAndSettle(); // Ease in sine (accelerating). - double accelerateIntepolation(double fraction) { + double accelerateInterpolation(double fraction) { return 1.0 - math.cos((fraction * math.pi) / 2.0); } @@ -7435,8 +7435,8 @@ void main() { }) { const double indicatorWeight = 3.0; final double tabChangeProgress = (controller.index - controller.animation!.value).abs(); - final double leftFraction = accelerateIntepolation(tabChangeProgress); - final double rightFraction = accelerateIntepolation(tabChangeProgress); + final double leftFraction = accelerateInterpolation(tabChangeProgress); + final double rightFraction = accelerateInterpolation(tabChangeProgress); final RRect rrect = RRect.fromLTRBAndCorners( lerpDouble(rect.left, targetRect.left, leftFraction)!, diff --git a/packages/flutter/test/material/text_button_test.dart b/packages/flutter/test/material/text_button_test.dart index 158be300818..75344ce2538 100644 --- a/packages/flutter/test/material/text_button_test.dart +++ b/packages/flutter/test/material/text_button_test.dart @@ -2304,7 +2304,7 @@ void main() { expect(material.color, backgroundColor); }); - testWidgets('Default iconAlignment', (WidgetTester tester) async { + testWidgets('Default TextButton icon alignment', (WidgetTester tester) async { Widget buildWidget({ required TextDirection textDirection }) { return MaterialApp( home: Directionality( @@ -2339,7 +2339,7 @@ void main() { expect(buttonTopRight.dx, iconTopRight.dx + 12.0); // 12.0 - padding between icon and button edge. }); - testWidgets('iconAlignment can be customized', (WidgetTester tester) async { + testWidgets('TextButton icon alignment can be customized', (WidgetTester tester) async { Widget buildWidget({ required TextDirection textDirection, required IconAlignment iconAlignment, @@ -2416,6 +2416,35 @@ void main() { expect(buttonTopLeft.dx, iconTopLeft.dx - 16.0); // 16.0 - padding between icon and button edge. }); + testWidgets('TextButton icon alignment respects ButtonStyle.iconAlignment', (WidgetTester tester) async { + Widget buildButton({ IconAlignment? iconAlignment }) { + return MaterialApp( + home: Center( + child: TextButton.icon( + style: ButtonStyle(iconAlignment: iconAlignment), + onPressed: () {}, + icon: const Icon(Icons.add), + label: const Text('button'), + ), + ), + ); + } + + await tester.pumpWidget(buildButton()); + + final Offset buttonTopLeft = tester.getTopLeft(find.byType(Material).last); + final Offset iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add)); + + expect(buttonTopLeft.dx, iconTopLeft.dx - 12.0); + + await tester.pumpWidget(buildButton(iconAlignment: IconAlignment.end)); + + final Offset buttonTopRight = tester.getTopRight(find.byType(Material).last); + final Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); + + expect(buttonTopRight.dx, iconTopRight.dx + 16.0); + }); + testWidgets('treats a hovering stylus like a mouse', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); @@ -2476,6 +2505,7 @@ void main() { style: TextButton.styleFrom( iconColor: iconColor, iconSize: iconSize, + iconAlignment: IconAlignment.end, disabledIconColor: disabledIconColor, ), onPressed: enabled ? () {} : null, @@ -2495,5 +2525,9 @@ void main() { // Test disabled button. await tester.pumpWidget(buildButton(enabled: false)); expect(iconStyle(tester, Icons.add).color, disabledIconColor); + + final Offset buttonTopRight = tester.getTopRight(find.byType(Material).last); + final Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); + expect(buttonTopRight.dx, iconTopRight.dx + 16.0); }); } diff --git a/packages/flutter/test/material/text_button_theme_test.dart b/packages/flutter/test/material/text_button_theme_test.dart index 298febae522..407d3c22027 100644 --- a/packages/flutter/test/material/text_button_theme_test.dart +++ b/packages/flutter/test/material/text_button_theme_test.dart @@ -239,7 +239,7 @@ void main() { }); }); - testWidgets('Material3: Theme shadowColor', (WidgetTester tester) async { + testWidgets('Material3 - TextButton repsects Theme shadowColor', (WidgetTester tester) async { const ColorScheme colorScheme = ColorScheme.light(); const Color shadowColor = Color(0xff000001); const Color overriddenColor = Color(0xff000002); @@ -310,7 +310,7 @@ void main() { expect(material.shadowColor, shadowColor); }); - testWidgets('Material2: Theme shadowColor', (WidgetTester tester) async { + testWidgets('Material2 - TextButton repsects Theme shadowColor', (WidgetTester tester) async { const ColorScheme colorScheme = ColorScheme.light(); const Color shadowColor = Color(0xff000001); const Color overriddenColor = Color(0xff000002); @@ -379,4 +379,40 @@ void main() { material = tester.widget(buttonMaterialFinder); expect(material.shadowColor, shadowColor); }); + + testWidgets('TextButton.icon respects TextButtonTheme ButtonStyle.iconAlignment', (WidgetTester tester) async { + Widget buildButton({ IconAlignment? iconAlignment }) { + return MaterialApp( + theme: ThemeData( + textButtonTheme: TextButtonThemeData( + style: ButtonStyle(iconAlignment: iconAlignment), + ), + ), + home: Scaffold( + body: Center( + child: TextButton.icon( + onPressed: () {}, + icon: const Icon(Icons.add), + label: const Text('button'), + ), + ), + ), + ); + } + + await tester.pumpWidget(buildButton()); + + final Offset buttonTopLeft = tester.getTopLeft(find.byType(Material).last); + final Offset iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add)); + + expect(buttonTopLeft.dx, iconTopLeft.dx - 12.0); + + await tester.pumpWidget(buildButton(iconAlignment: IconAlignment.end)); + await tester.pumpAndSettle(); + + final Offset buttonTopRight = tester.getTopRight(find.byType(Material).last); + final Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); + + expect(buttonTopRight.dx, iconTopRight.dx + 16.0); + }); } diff --git a/packages/flutter/test/material/time_picker_test.dart b/packages/flutter/test/material/time_picker_test.dart index 07b43390593..615b439049c 100644 --- a/packages/flutter/test/material/time_picker_test.dart +++ b/packages/flutter/test/material/time_picker_test.dart @@ -2074,7 +2074,6 @@ void main() { // Enter invalid hour. await tester.enterText(find.byType(TextField).first, 'AB'); await tester.tap(find.text(okString)); - await tester.pumpAndSettle(); expect(tester.getSize(findBorderPainter().first), const Size(96.0, 70.0)); }); @@ -2093,7 +2092,6 @@ void main() { // Enter invalid hour. await tester.enterText(find.byType(TextField).first, 'AB'); await tester.tap(find.text(okString)); - await tester.pumpAndSettle(); expect(tester.getSize(findBorderPainter().first), const Size(96.0, 70.0)); }); @@ -2214,6 +2212,7 @@ class _TimePickerLauncher extends StatefulWidget { _TimePickerLauncherState createState() => _TimePickerLauncherState(); } +@pragma('vm:entry-point') class _TimePickerLauncherState extends State<_TimePickerLauncher> with RestorationMixin { @override String? get restorationId => widget.restorationId; diff --git a/packages/flutter/test/material/time_picker_theme_test.dart b/packages/flutter/test/material/time_picker_theme_test.dart index 3251ddfbf4a..3c7207380ab 100644 --- a/packages/flutter/test/material/time_picker_theme_test.dart +++ b/packages/flutter/test/material/time_picker_theme_test.dart @@ -872,7 +872,6 @@ void main() { // Enter invalid hour. await tester.enterText(find.byType(TextField).first, 'AB'); await tester.tap(find.text('OK')); - await tester.pumpAndSettle(); expect(tester.getSize(findBorderPainter().first), const Size(96.0, 72.0)); }); @@ -890,7 +889,6 @@ void main() { // Enter invalid hour. await tester.enterText(find.byType(TextField).first, 'AB'); await tester.tap(find.text('OK')); - await tester.pumpAndSettle(); expect(tester.getSize(findBorderPainter().first), const Size(96.0, 70.0)); }); diff --git a/packages/flutter/test/material/tooltip_test.dart b/packages/flutter/test/material/tooltip_test.dart index e9046f7f6a1..70f6e9a5b44 100644 --- a/packages/flutter/test/material/tooltip_test.dart +++ b/packages/flutter/test/material/tooltip_test.dart @@ -3091,6 +3091,38 @@ void main() { expect(selectedText, isNot(contains('A'))); }); + + testWidgets('Tooltip mouse cursor behavior', (WidgetTester tester) async { + const SystemMouseCursor customCursor = SystemMouseCursors.grab; + + await tester.pumpWidget( + const MaterialApp( + home: Center( + child: Tooltip( + message: tooltipText, + mouseCursor: customCursor, + child: SizedBox.square(dimension: 50), + ), + ), + ), + ); + + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + await gesture.addPointer(location: const Offset(10, 10)); + await tester.pump(); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.basic, + ); + + final Offset chip = tester.getCenter(find.byType(Tooltip)); + await gesture.moveTo(chip); + await tester.pump(); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + customCursor, + ); + }); } Future setWidgetForTooltipMode( diff --git a/packages/flutter/test/painting/_network_image_test_web.dart b/packages/flutter/test/painting/_network_image_test_web.dart index a5aa25881e7..f55143c7b5f 100644 --- a/packages/flutter/test/painting/_network_image_test_web.dart +++ b/packages/flutter/test/painting/_network_image_test_web.dart @@ -2,10 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:async'; + import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; +import 'package:flutter/material.dart' hide NetworkImage; import 'package:flutter/src/painting/_network_image_web.dart'; +import 'package:flutter/src/painting/_web_image_info_web.dart'; import 'package:flutter/src/web.dart' as web_shim; +import 'package:flutter/src/widgets/_web_image_web.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:web/web.dart' as web; @@ -14,6 +18,7 @@ import '_test_http_request.dart'; void runTests() { tearDown(() { debugRestoreHttpRequestFactory(); + debugRestoreImgElementFactory(); }); testWidgets('loads an image from the network with headers', @@ -64,14 +69,21 @@ void runTests() { ); await tester.pumpWidget(image); - expect((tester.takeException() as web.ProgressEvent).type, 'test error'); + expect( + tester.takeException(), + isA().having( + (NetworkImageLoadException e) => e.statusCode, + 'status code', + 404, + ), + ); }); testWidgets('loads an image from the network with empty response', (WidgetTester tester) async { final TestHttpRequest testHttpRequest = TestHttpRequest() ..status = 200 - ..mockEvent = MockEvent('load', web.Event('test error')) + ..mockEvent = MockEvent('load', web.Event('successful load')) ..response = (Uint8List.fromList([])).buffer; httpRequestFactory = () { @@ -92,4 +104,201 @@ void runTests() { expect(tester.takeException().toString(), 'HTTP request failed, statusCode: 200, https://www.example.com/images/frame3.png'); }); + + testWidgets('emits a WebImageInfo if the image is cross-origin', + (WidgetTester tester) async { + final TestHttpRequest failingRequest = TestHttpRequest() + ..status = 500 + ..mockEvent = MockEvent('load', web.Event('bytes inaccessible')) + ..response = (Uint8List.fromList([])).buffer; + final TestImgElement testImg = TestImgElement(); + + httpRequestFactory = () { + return failingRequest.getMock() as web_shim.XMLHttpRequest; + }; + + imgElementFactory = () { + return testImg.getMock() as web_shim.HTMLImageElement; + }; + + const NetworkImage networkImage = NetworkImage('https://www.example.com/images/frame4.png'); + ImageInfo? imageInfo; + Object? recordedError; + Completer? imageCompleter; + await tester.runAsync(() async { + imageCompleter = Completer(); + final ImageStream stream = networkImage.resolve(ImageConfiguration.empty); + stream.addListener(ImageStreamListener((ImageInfo info, bool isSync) { + imageInfo = info; + imageCompleter!.complete(); + }, onError: (Object error, StackTrace? stackTrace) { + recordedError = error; + imageCompleter!.complete(); + })); + }); + await tester.runAsync(() async { + testImg.decodeSuccess(); + await imageCompleter!.future; + }); + expect(recordedError, isNull); + expect(imageInfo, isA()); + + final WebImageInfo webImageInfo = imageInfo! as WebImageInfo; + expect(webImageInfo.htmlImage.src, equals('https://www.example.com/images/frame4.png')); + }, skip: !isSkiaWeb); + + testWidgets('emits an error if the image is cross-origin but fails to decode', + (WidgetTester tester) async { + final TestHttpRequest failingRequest = TestHttpRequest() + ..status = 500 + ..mockEvent = MockEvent('load', web.Event('bytes inaccessible')) + ..response = (Uint8List.fromList([])).buffer; + final TestImgElement testImg = TestImgElement(); + + httpRequestFactory = () { + return failingRequest.getMock() as web_shim.XMLHttpRequest; + }; + + imgElementFactory = () { + return testImg.getMock() as web_shim.HTMLImageElement; + }; + + const NetworkImage networkImage = NetworkImage('https://www.example.com/images/frame5.png'); + ImageInfo? imageInfo; + Object? recordedError; + Completer? imageCompleter; + await tester.runAsync(() async { + imageCompleter = Completer(); + final ImageStream stream = networkImage.resolve(ImageConfiguration.empty); + stream.addListener(ImageStreamListener((ImageInfo info, bool isSync) { + imageInfo = info; + imageCompleter!.complete(); + }, onError: (Object error, StackTrace? stackTrace) { + recordedError = error; + imageCompleter!.complete(); + })); + }); + await tester.runAsync(() async { + testImg.decodeFailure(); + await imageCompleter!.future; + }); + expect(recordedError, isNotNull); + expect(imageInfo, isNull); + }, skip: !isSkiaWeb); + + testWidgets('Image renders an image using a Platform View if the image info is WebImageInfo', + (WidgetTester tester) async { + final TestImgElement testImg = TestImgElement(); + + final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(); + final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); + + await tester.pumpWidget( + Image( + image: imageProvider, + ), + ); + + // Before getting a WebImageInfo, the Image resolves to a RawImage. + expect(find.byType(RawImage), findsOneWidget); + expect(find.byType(RawWebImage), findsNothing); + expect(find.byType(PlatformViewLink), findsNothing); + streamCompleter.setData(imageInfo: WebImageInfo(testImg.getMock() as web_shim.HTMLImageElement)); + await tester.pump(); + expect(find.byType(RawImage), findsNothing); + // After getting a WebImageInfo, the Image uses a Platform View to render. + expect(find.byType(RawWebImage), findsOneWidget); + expect(find.byType(PlatformViewLink), findsOneWidget); + }, skip: !isSkiaWeb); +} + +class _TestImageProvider extends ImageProvider { + _TestImageProvider({required ImageStreamCompleter streamCompleter}) { + _streamCompleter = streamCompleter; + } + + final Completer _completer = Completer(); + late ImageStreamCompleter _streamCompleter; + + @override + Future obtainKey(ImageConfiguration configuration) { + return SynchronousFuture<_TestImageProvider>(this); + } + + @override + ImageStreamCompleter loadImage(Object key, ImageDecoderCallback decode) { + return _streamCompleter; + } + + void complete(web_shim.HTMLImageElement image) { + _completer.complete(WebImageInfo(image)); + } + + void fail(Object exception, StackTrace? stackTrace) { + _completer.completeError(exception, stackTrace); + } + + @override + String toString() => '${describeIdentity(this)}()'; +} + +/// An [ImageStreamCompleter] that gives access to the added listeners. +/// +/// Such an access to listeners is hacky, +/// because it breaks encapsulation by allowing to invoke listeners without +/// taking care about lifecycle of the created images, that may result in not disposed images. +/// +/// That's why some tests that use it are opted out from leak tracking. +class _TestImageStreamCompleter extends ImageStreamCompleter { + _TestImageStreamCompleter(); + + ImageInfo? _currentImage; + final Set listeners = {}; + + @override + void addListener(ImageStreamListener listener) { + listeners.add(listener); + if (_currentImage != null) { + listener.onImage(_currentImage!.clone(), true); + } + } + + @override + void removeListener(ImageStreamListener listener) { + listeners.remove(listener); + } + + void setData({ + ImageInfo? imageInfo, + ImageChunkEvent? chunkEvent, + }) { + if (imageInfo != null) { + _currentImage?.dispose(); + _currentImage = imageInfo; + } + final List localListeners = listeners.toList(); + for (final ImageStreamListener listener in localListeners) { + if (imageInfo != null) { + listener.onImage(imageInfo.clone(), false); + } + if (chunkEvent != null && listener.onChunk != null) { + listener.onChunk!(chunkEvent); + } + } + } + + void setError({ + required Object exception, + StackTrace? stackTrace, + }) { + final List localListeners = listeners.toList(); + for (final ImageStreamListener listener in localListeners) { + listener.onError?.call(exception, stackTrace); + } + } + + void dispose() { + final List listenersCopy = listeners.toList(); + listenersCopy.forEach(removeListener); + } } diff --git a/packages/flutter/test/painting/_test_http_request.dart b/packages/flutter/test/painting/_test_http_request.dart index 86e03ae80c1..bb3e3baa8e3 100644 --- a/packages/flutter/test/painting/_test_http_request.dart +++ b/packages/flutter/test/painting/_test_http_request.dart @@ -83,3 +83,69 @@ class MockEvent { final String type; final web.Event event; } + +@JS() +@staticInterop +@anonymous +class ImgElementMock { + external factory ImgElementMock({ + JSFunction? decode, + }); +} + +class TestImgElement { + TestImgElement() { + _mock = ImgElementMock(decode: decode.toJS); + final JSAny mock = _mock as JSAny; + objectDefineProperty(mock, 'src', + { + 'get': (() => src).toJS, + 'set': ((JSString newValue) { + src = newValue.toDart; + }).toJS, + }.jsify()!, + ); + objectDefineProperty(mock, 'naturalWidth', + { + 'get': (() => naturalWidth).toJS, + 'set': ((JSNumber newValue) { + naturalWidth = newValue.toDartInt; + }).toJS, + }.jsify()!, + ); + objectDefineProperty(mock, 'naturalHeight', + { + 'get': (() => naturalHeight).toJS, + 'set': ((JSNumber newValue) { + naturalHeight = newValue.toDartInt; + }).toJS, + }.jsify()!, + ); + } + + late ImgElementMock _mock; + + String src = ''; + int naturalWidth = -1; + int naturalHeight = -1; + + late JSFunction _resolveFunc; + late JSFunction _rejectFunc; + + JSPromise decode() { + return JSPromise((JSFunction resolveFunc, JSFunction rejectFunc) { + _resolveFunc = resolveFunc; + _rejectFunc = rejectFunc; + }.toJS); + } + + void decodeSuccess() { + _resolveFunc.callAsFunction(); + } + + void decodeFailure() { + _rejectFunc.callAsFunction(); + } + + web.HTMLImageElement getMock() => _mock as web.HTMLImageElement; +} diff --git a/packages/flutter/test/painting/image_provider_network_image_test.dart b/packages/flutter/test/painting/image_provider_network_image_test.dart index 2c56a0a5d19..18559f2f750 100644 --- a/packages/flutter/test/painting/image_provider_network_image_test.dart +++ b/packages/flutter/test/painting/image_provider_network_image_test.dart @@ -242,7 +242,7 @@ void main() { const NetworkImage provider = NetworkImage(url); - final MultiFrameImageStreamCompleter completer = provider.loadBuffer(provider, noOpDecoderBufferCallback) as MultiFrameImageStreamCompleter; + final ImageStreamCompleter completer = provider.loadBuffer(provider, noOpDecoderBufferCallback); expect(completer.debugLabel, url); }); diff --git a/packages/flutter/test/physics/spring_simulation_test.dart b/packages/flutter/test/physics/spring_simulation_test.dart new file mode 100644 index 00000000000..57fb75fdfdb --- /dev/null +++ b/packages/flutter/test/physics/spring_simulation_test.dart @@ -0,0 +1,35 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/physics.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('When snapToEnd is set, value is exactly `end` after completion', () { + final SpringDescription description = SpringDescription.withDampingRatio(mass: 1.0, stiffness: 400); + const double time = 0.4; + + final SpringSimulation regularSimulation = SpringSimulation( + description, + 0, + 1, + 0, + tolerance: const Tolerance(distance: 0.1, velocity: 0.1), + ); + expect(regularSimulation.x(time), lessThan(1)); + expect(regularSimulation.dx(time), greaterThan(0)); + + final SpringSimulation snappingSimulation = SpringSimulation( + description, + 0, + 1, + 0, + snapToEnd: true, + tolerance: const Tolerance(distance: 0.1, velocity: 0.1), + ); + // Must be exactly equal + expect(snappingSimulation.x(time), 1); + expect(snappingSimulation.dx(time), 0); + }); +} diff --git a/packages/flutter/test/rendering/editable_test.dart b/packages/flutter/test/rendering/editable_test.dart index 4253499dc90..5662be4f925 100644 --- a/packages/flutter/test/rendering/editable_test.dart +++ b/packages/flutter/test/rendering/editable_test.dart @@ -197,8 +197,9 @@ void main() { editable.paint(context, paintOffset); final List leaderLayers = context.pushedLayers.whereType().toList(); - expect(leaderLayers, hasLength(1), reason: '_paintHandleLayers will paint a LeaderLayer'); - expect(leaderLayers.single.offset, endpoint + paintOffset, reason: 'offset should respect paintOffset'); + expect(leaderLayers, hasLength(2), reason: '_paintHandleLayers will paint LeaderLayers'); + expect(leaderLayers.first.offset, endpoint + paintOffset, reason: 'offset should respect paintOffset'); + expect(leaderLayers.last.offset, endpoint + paintOffset, reason: 'offset should respect paintOffset'); }); // Test that clipping will be used even when the text fits within the visible diff --git a/packages/flutter/test/rendering/object_test.dart b/packages/flutter/test/rendering/object_test.dart index e685b907571..f38c0f00559 100644 --- a/packages/flutter/test/rendering/object_test.dart +++ b/packages/flutter/test/rendering/object_test.dart @@ -377,6 +377,44 @@ void main() { root.buildScene(ui.SceneBuilder()).dispose(); expect(calledBack, true); }); + + test('Change isRepaintBoundary after both markNeedsCompositedLayerUpdate and markNeedsPaint', () { + List? caughtErrors; + TestRenderingFlutterBinding.instance.onErrors = () { + caughtErrors = TestRenderingFlutterBinding.instance.takeAllFlutterErrorDetails().toList(); + }; + final TestRenderObject object = TestRenderObject(allowPaintBounds: true); + object.isRepaintBoundary = true; + object.attach(TestRenderingFlutterBinding.instance.pipelineOwner); + object.layout(const BoxConstraints.tightForFinite()); + PaintingContext.repaintCompositedChild(object, debugAlsoPaintedParent: true); + + object.markNeedsCompositedLayerUpdate(); + object.markNeedsPaint(); + object.isRepaintBoundary = false; + object.markNeedsCompositingBitsUpdate(); + TestRenderingFlutterBinding.instance.pumpCompleteFrame(); + expect(caughtErrors, isNull); + }); + + test('ContainerParentDataMixin asserts parentData type', () { + final TestRenderObject renderObject = TestRenderObjectWithoutSetupParentData(); + final TestRenderObject child = TestRenderObject(); + expect( + () => renderObject.add(child), + throwsA( + isA().having( + (AssertionError error) => error.toString(), + 'description', + contains( + 'A child of TestRenderObjectWithoutSetupParentData has parentData of type ParentData, ' + 'which does not conform to TestRenderObjectParentData. Class using ContainerRenderObjectMixin ' + 'should override setupParentData() to set parentData to type TestRenderObjectParentData.' + ), + ), + ), + ); + }); } @@ -485,6 +523,16 @@ class TestRenderObject extends RenderObject with ContainerRenderObjectMixin{ + 'method': 'Scribe.unsupportedMessage', + }); + + final ByteData? response = await binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/scribe', + messageBytes, + null, + ); + + // When a MissingPluginException is thrown, it is caught and a null response + // is returned. + expect(response, isNull); + }, skip: kIsWeb); // [intended] + + for (final bool? returnValue in [false, true, null]) { + test('Scribe.isStylusHandwritingAvailable calls through to platform channel', () async { + final List calls = []; + binding.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.scribe, (MethodCall methodCall) { + calls.add(methodCall); + return Future.value(returnValue); + }); + + if (returnValue == null) { + expect(() async { + await Scribe.isStylusHandwritingAvailable(); + }, throwsA(isA())); + } else { + expect(await Scribe.isStylusHandwritingAvailable(), returnValue); + } + + expect(calls, hasLength(1)); + expect(calls.first.method, 'Scribe.isStylusHandwritingAvailable'); + }, skip: kIsWeb); // [intended] + } + + for (final bool? returnValue in [false, true, null]) { + test('Scribe.isFeatureAvailable calls through to platform channel', () async { + final List calls = []; + binding.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.scribe, (MethodCall methodCall) { + calls.add(methodCall); + return Future.value(returnValue); + }); + + if (returnValue == null) { + expect(() async { + await Scribe.isFeatureAvailable(); + }, throwsA(isA())); + } else { + expect(await Scribe.isFeatureAvailable(), returnValue); + } + + expect(calls, hasLength(1)); + expect(calls.first.method, 'Scribe.isFeatureAvailable'); + }, skip: kIsWeb); // [intended] + } + + test('Scribe.startStylusHandwriting calls through to platform channel', () async { + final List calls = []; + binding.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.scribe, (MethodCall methodCall) { + calls.add(methodCall); + return Future.value(); + }); + + Scribe.startStylusHandwriting(); + expect(calls, hasLength(1)); + expect(calls.first.method, 'Scribe.startStylusHandwriting'); + }, skip: kIsWeb); // [intended] +} diff --git a/packages/flutter/test/services/text_input_test.dart b/packages/flutter/test/services/text_input_test.dart index 215e9dc0c1c..f369272d560 100644 --- a/packages/flutter/test/services/text_input_test.dart +++ b/packages/flutter/test/services/text_input_test.dart @@ -348,6 +348,7 @@ void main() { expect(TextInputType.name.toString(), 'TextInputType(name: TextInputType.name, signed: null, decimal: null)'); expect(TextInputType.streetAddress.toString(), 'TextInputType(name: TextInputType.address, signed: null, decimal: null)'); expect(TextInputType.none.toString(), 'TextInputType(name: TextInputType.none, signed: null, decimal: null)'); + expect(TextInputType.webSearch.toString(), 'TextInputType(name: TextInputType.webSearch, signed: null, decimal: null)'); expect(text == number, false); expect(number == number2, true); @@ -376,6 +377,7 @@ void main() { expect(TextInputType.name.index, 8); expect(TextInputType.streetAddress.index, 9); expect(TextInputType.none.index, 10); + expect(TextInputType.webSearch.index, 11); expect(TextEditingValue.empty.toString(), 'TextEditingValue(text: \u2524\u251C, selection: ${const TextSelection.collapsed(offset: -1)}, composing: ${TextRange.empty})'); diff --git a/packages/flutter/test/widgets/app_test.dart b/packages/flutter/test/widgets/app_test.dart index 3265decd679..117898ba618 100644 --- a/packages/flutter/test/widgets/app_test.dart +++ b/packages/flutter/test/widgets/app_test.dart @@ -153,7 +153,7 @@ void main() { expect(checked, isTrue); }, variant: KeySimulatorTransitModeVariant.all()); - testWidgets('Title is not created if title is not passed and kIsweb', (WidgetTester tester) async { + testWidgets('Title is not created if title is not passed and kIsWeb', (WidgetTester tester) async { await tester.pumpWidget( WidgetsApp( color: const Color(0xFF123456), diff --git a/packages/flutter/test/widgets/custom_painter_test.dart b/packages/flutter/test/widgets/custom_painter_test.dart index af165401282..6e7ed76e614 100644 --- a/packages/flutter/test/widgets/custom_painter_test.dart +++ b/packages/flutter/test/widgets/custom_painter_test.dart @@ -355,7 +355,8 @@ void _defineTests() { )); final Set allActions = SemanticsAction.values.toSet() ..remove(SemanticsAction.customAction) // customAction is not user-exposed. - ..remove(SemanticsAction.showOnScreen); // showOnScreen is not user-exposed + ..remove(SemanticsAction.showOnScreen) // showOnScreen is not user-exposed + ..remove(SemanticsAction.scrollToOffset); // scrollToOffset is not user-exposed const int expectedId = 2; final TestSemantics expectedSemantics = TestSemantics.root( @@ -405,6 +406,7 @@ void _defineTests() { case SemanticsAction.scrollLeft: case SemanticsAction.scrollRight: case SemanticsAction.scrollUp: + case SemanticsAction.scrollToOffset: case SemanticsAction.showOnScreen: case SemanticsAction.tap: case SemanticsAction.focus: diff --git a/packages/flutter/test/widgets/default_colors_test.dart b/packages/flutter/test/widgets/default_colors_test.dart index 916fba0aa3b..367ca487bff 100644 --- a/packages/flutter/test/widgets/default_colors_test.dart +++ b/packages/flutter/test/widgets/default_colors_test.dart @@ -69,11 +69,8 @@ void main() { testWidgets('Default text selection color', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); final OverlayEntry overlayEntry = OverlayEntry( builder: (BuildContext context) => SelectableRegion( - focusNode: focusNode, selectionControls: emptyTextSelectionControls, child: Align( key: key, diff --git a/packages/flutter/test/widgets/draggable_test.dart b/packages/flutter/test/widgets/draggable_test.dart index b2999e5fbfd..57c3b04a792 100644 --- a/packages/flutter/test/widgets/draggable_test.dart +++ b/packages/flutter/test/widgets/draggable_test.dart @@ -3362,7 +3362,7 @@ void main() { TestSemantics( id: 9, flags: [SemanticsFlag.hasImplicitScrolling], - actions: [SemanticsAction.scrollLeft], + actions: [SemanticsAction.scrollLeft, SemanticsAction.scrollToOffset], children: [ TestSemantics( id: 5, @@ -3430,6 +3430,7 @@ void main() { children: [ TestSemantics( id: 9, + actions: [SemanticsAction.scrollToOffset], flags: [SemanticsFlag.hasImplicitScrolling], children: [ TestSemantics( diff --git a/packages/flutter/test/widgets/editable_text_scribble_test.dart b/packages/flutter/test/widgets/editable_text_scribble_test.dart new file mode 100644 index 00000000000..873db79300e --- /dev/null +++ b/packages/flutter/test/widgets/editable_text_scribble_test.dart @@ -0,0 +1,743 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'editable_text_utils.dart'; + +void main() { + const TextStyle textStyle = TextStyle(); + const Color cursorColor = Color.fromARGB(0xFF, 0xFF, 0x00, 0x00); + late TextEditingController controller; + late FocusNode focusNode; + + setUp(() async { + controller = TextEditingController(); + focusNode = FocusNode(debugLabel: 'EditableText Node'); + }); + + tearDown(() { + controller.dispose(); + focusNode.dispose(); + }); + + testWidgets('selection rects re-sent when refocused', (WidgetTester tester) async { + final List> log = >[]; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { + if (methodCall.method == 'TextInput.setSelectionRects') { + final List args = methodCall.arguments as List; + final List selectionRects = []; + for (final dynamic rect in args) { + selectionRects.add(SelectionRect( + position: (rect as List)[4] as int, + bounds: Rect.fromLTWH(rect[0] as double, rect[1] as double, rect[2] as double, rect[3] as double), + )); + } + log.add(selectionRects); + } + return null; + }); + + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + controller.text = 'Text1'; + + Future pumpEditableText({ double? width, double? height, TextAlign textAlign = TextAlign.start }) async { + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + width: width, + height: height, + child: EditableText( + controller: controller, + textAlign: textAlign, + scrollController: scrollController, + maxLines: null, + focusNode: focusNode, + cursorWidth: 0, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + ), + ), + ), + ), + ), + ); + } + + const List expectedRects = [ + SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), + SelectionRect(position: 1, bounds: Rect.fromLTRB(14.0, 0.0, 28.0, 14.0)), + SelectionRect(position: 2, bounds: Rect.fromLTRB(28.0, 0.0, 42.0, 14.0)), + SelectionRect(position: 3, bounds: Rect.fromLTRB(42.0, 0.0, 56.0, 14.0)), + SelectionRect(position: 4, bounds: Rect.fromLTRB(56.0, 0.0, 70.0, 14.0)) + ]; + + await pumpEditableText(); + expect(log, isEmpty); + + await tester.showKeyboard(find.byType(EditableText)); + // First update. + expect(log.single, expectedRects); + log.clear(); + + await tester.pumpAndSettle(); + expect(log, isEmpty); + + focusNode.unfocus(); + await tester.pumpAndSettle(); + expect(log, isEmpty); + + focusNode.requestFocus(); + //await tester.showKeyboard(find.byType(EditableText)); + await tester.pumpAndSettle(); + // Should re-receive the same rects. + expect(log.single, expectedRects); + log.clear(); + + // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. + }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); // [intended] + + testWidgets('Selection changes during Scribble interaction should have the scribble cause', (WidgetTester tester) async { + controller.text = 'Lorem ipsum dolor sit amet'; + late SelectionChangedCause selectionCause; + + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { + if (cause != null) { + selectionCause = cause; + } + }, + ), + ), + ); + + await tester.showKeyboard(find.byType(EditableText)); + + // A normal selection update from the framework has 'keyboard' as the cause. + tester.testTextInput.updateEditingValue(TextEditingValue( + text: controller.text, + selection: const TextSelection(baseOffset: 2, extentOffset: 3), + )); + await tester.pumpAndSettle(); + + expect(selectionCause, SelectionChangedCause.keyboard); + + // A selection update during a scribble interaction has 'scribble' as the cause. + await tester.testTextInput.startScribbleInteraction(); + tester.testTextInput.updateEditingValue(TextEditingValue( + text: controller.text, + selection: const TextSelection(baseOffset: 3, extentOffset: 4), + )); + await tester.pumpAndSettle(); + + expect(selectionCause, SelectionChangedCause.scribble); + + await tester.testTextInput.finishScribbleInteraction(); + }, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); + + testWidgets('Requests focus and changes the selection when onScribbleFocus is called', (WidgetTester tester) async { + controller.text = 'Lorem ipsum dolor sit amet'; + late SelectionChangedCause selectionCause; + + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { + if (cause != null) { + selectionCause = cause; + } + }, + ), + ), + ); + + await tester.testTextInput.scribbleFocusElement(TextInput.scribbleClients.keys.first, Offset.zero); + + expect(focusNode.hasFocus, true); + expect(selectionCause, SelectionChangedCause.scribble); + + // On web, we should rely on the browser's implementation of Scribble, so the selection changed cause + // will never be SelectionChangedCause.scribble. + }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); // [intended] + + testWidgets('Declares itself for Scribble interaction if the bounds overlap the scribble rect and the widget is touchable', (WidgetTester tester) async { + controller.text = 'Lorem ipsum dolor sit amet'; + + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + ), + ), + ); + + final List elementEntry = [TextInput.scribbleClients.keys.first, 0.0, 0.0, 800.0, 600.0]; + + List> elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(0, 0, 1, 1)); + expect(elements.first, containsAll(elementEntry)); + + // Touch is outside the bounds of the widget. + elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(-1, -1, 1, 1)); + expect(elements.length, 0); + + // Widget is read only. + await tester.pumpWidget( + MaterialApp( + home: EditableText( + readOnly: true, + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + ), + ), + ); + + elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(0, 0, 1, 1)); + expect(elements.length, 0); + + // Widget is not touchable. + await tester.pumpWidget( + MaterialApp( + home: Stack(children: [ + EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + ), + Positioned( + left: 0, + top: 0, + right: 0, + bottom: 0, + child: Container(color: Colors.black), + ), + ], + ), + ), + ); + + elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(0, 0, 1, 1)); + expect(elements.length, 0); + + // Widget has scribble disabled. + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + stylusHandwritingEnabled: false, + ), + ), + ); + + elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(0, 0, 1, 1)); + expect(elements.length, 0); + + + // On web, we should rely on the browser's implementation of Scribble, so the engine will + // never request the scribble elements. + }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); // [intended] + + testWidgets('single line Scribble fields can show a horizontal placeholder', (WidgetTester tester) async { + controller.text = 'Lorem ipsum dolor sit amet'; + + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + ), + ), + ); + + await tester.showKeyboard(find.byType(EditableText)); + + tester.testTextInput.updateEditingValue(TextEditingValue( + text: controller.text, + selection: const TextSelection(baseOffset: 5, extentOffset: 5), + )); + await tester.pumpAndSettle(); + + await tester.testTextInput.scribbleInsertPlaceholder(); + await tester.pumpAndSettle(); + + TextSpan textSpan = findRenderEditable(tester).text! as TextSpan; + expect(textSpan.children!.length, 3); + expect((textSpan.children![0] as TextSpan).text, 'Lorem'); + expect(textSpan.children![1] is WidgetSpan, true); + expect((textSpan.children![2] as TextSpan).text, ' ipsum dolor sit amet'); + + await tester.testTextInput.scribbleRemovePlaceholder(); + await tester.pumpAndSettle(); + + textSpan = findRenderEditable(tester).text! as TextSpan; + expect(textSpan.children, null); + expect(textSpan.text, 'Lorem ipsum dolor sit amet'); + + // Widget has scribble disabled. + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + stylusHandwritingEnabled: false, + ), + ), + ); + + await tester.showKeyboard(find.byType(EditableText)); + + tester.testTextInput.updateEditingValue(TextEditingValue( + text: controller.text, + selection: const TextSelection(baseOffset: 5, extentOffset: 5), + )); + await tester.pumpAndSettle(); + + await tester.testTextInput.scribbleInsertPlaceholder(); + await tester.pumpAndSettle(); + + textSpan = findRenderEditable(tester).text! as TextSpan; + expect(textSpan.children, null); + expect(textSpan.text, 'Lorem ipsum dolor sit amet'); + + // On web, we should rely on the browser's implementation of Scribble, so the framework + // will not handle placeholders. + }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); // [intended] + + testWidgets('multiline Scribble fields can show a vertical placeholder', (WidgetTester tester) async { + controller.text = 'Lorem ipsum dolor sit amet'; + + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + maxLines: 2, + ), + ), + ); + + await tester.showKeyboard(find.byType(EditableText)); + + tester.testTextInput.updateEditingValue(TextEditingValue( + text: controller.text, + selection: const TextSelection(baseOffset: 5, extentOffset: 5), + )); + await tester.pumpAndSettle(); + + await tester.testTextInput.scribbleInsertPlaceholder(); + await tester.pumpAndSettle(); + + TextSpan textSpan = findRenderEditable(tester).text! as TextSpan; + expect(textSpan.children!.length, 4); + expect((textSpan.children![0] as TextSpan).text, 'Lorem'); + expect(textSpan.children![1] is WidgetSpan, true); + expect(textSpan.children![2] is WidgetSpan, true); + expect((textSpan.children![3] as TextSpan).text, ' ipsum dolor sit amet'); + + await tester.testTextInput.scribbleRemovePlaceholder(); + await tester.pumpAndSettle(); + + textSpan = findRenderEditable(tester).text! as TextSpan; + expect(textSpan.children, null); + expect(textSpan.text, 'Lorem ipsum dolor sit amet'); + + // Widget has scribble disabled. + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + maxLines: 2, + stylusHandwritingEnabled: false, + ), + ), + ); + + await tester.showKeyboard(find.byType(EditableText)); + + tester.testTextInput.updateEditingValue(TextEditingValue( + text: controller.text, + selection: const TextSelection(baseOffset: 5, extentOffset: 5), + )); + await tester.pumpAndSettle(); + + await tester.testTextInput.scribbleInsertPlaceholder(); + await tester.pumpAndSettle(); + + textSpan = findRenderEditable(tester).text! as TextSpan; + expect(textSpan.children, null); + expect(textSpan.text, 'Lorem ipsum dolor sit amet'); + + // On web, we should rely on the browser's implementation of Scribble, so the framework + // will not handle placeholders. + }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); // [intended] + + testWidgets('selection rects are sent when they change', (WidgetTester tester) async { + addTearDown(tester.view.reset); + // Ensure selection rects are sent on iPhone (using SE 3rd gen size) + tester.view.physicalSize = const Size(750.0, 1334.0); + + final List> log = >[]; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) { + if (methodCall.method == 'TextInput.setSelectionRects') { + final List args = methodCall.arguments as List; + final List selectionRects = []; + for (final dynamic rect in args) { + selectionRects.add(SelectionRect( + position: (rect as List)[4] as int, + bounds: Rect.fromLTWH(rect[0] as double, rect[1] as double, rect[2] as double, rect[3] as double), + )); + } + log.add(selectionRects); + } + return null; + }); + + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + controller.text = 'Text1'; + + Future pumpEditableText({ double? width, double? height, TextAlign textAlign = TextAlign.start }) async { + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + width: width, + height: height, + child: EditableText( + controller: controller, + textAlign: textAlign, + scrollController: scrollController, + maxLines: null, + focusNode: focusNode, + cursorWidth: 0, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + ), + ), + ), + ), + ), + ); + } + + await pumpEditableText(); + expect(log, isEmpty); + + await tester.showKeyboard(find.byType(EditableText)); + // First update. + expect(log.single, const [ + SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), + SelectionRect(position: 1, bounds: Rect.fromLTRB(14.0, 0.0, 28.0, 14.0)), + SelectionRect(position: 2, bounds: Rect.fromLTRB(28.0, 0.0, 42.0, 14.0)), + SelectionRect(position: 3, bounds: Rect.fromLTRB(42.0, 0.0, 56.0, 14.0)), + SelectionRect(position: 4, bounds: Rect.fromLTRB(56.0, 0.0, 70.0, 14.0)) + ]); + log.clear(); + + await tester.pumpAndSettle(); + expect(log, isEmpty); + + await pumpEditableText(); + expect(log, isEmpty); + + // Change the width such that each character occupies a line. + await pumpEditableText(width: 20); + expect(log.single, const [ + SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), + SelectionRect(position: 1, bounds: Rect.fromLTRB(0.0, 14.0, 14.0, 28.0)), + SelectionRect(position: 2, bounds: Rect.fromLTRB(0.0, 28.0, 14.0, 42.0)), + SelectionRect(position: 3, bounds: Rect.fromLTRB(0.0, 42.0, 14.0, 56.0)), + SelectionRect(position: 4, bounds: Rect.fromLTRB(0.0, 56.0, 14.0, 70.0)) + ]); + log.clear(); + + await tester.enterText(find.byType(EditableText), 'Text1👨‍👩‍👦'); + await tester.pump(); + expect(log.single, const [ + SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), + SelectionRect(position: 1, bounds: Rect.fromLTRB(0.0, 14.0, 14.0, 28.0)), + SelectionRect(position: 2, bounds: Rect.fromLTRB(0.0, 28.0, 14.0, 42.0)), + SelectionRect(position: 3, bounds: Rect.fromLTRB(0.0, 42.0, 14.0, 56.0)), + SelectionRect(position: 4, bounds: Rect.fromLTRB(0.0, 56.0, 14.0, 70.0)), + SelectionRect(position: 5, bounds: Rect.fromLTRB(0.0, 70.0, 42.0, 84.0)), + ]); + log.clear(); + + // The 4th line will be partially visible. + await pumpEditableText(width: 20, height: 45); + expect(log.single, const [ + SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), + SelectionRect(position: 1, bounds: Rect.fromLTRB(0.0, 14.0, 14.0, 28.0)), + SelectionRect(position: 2, bounds: Rect.fromLTRB(0.0, 28.0, 14.0, 42.0)), + SelectionRect(position: 3, bounds: Rect.fromLTRB(0.0, 42.0, 14.0, 56.0)), + ]); + log.clear(); + + await pumpEditableText(width: 20, height: 45, textAlign: TextAlign.right); + // This is 1px off from being completely right-aligned. The 1px width is + // reserved for caret. + expect(log.single, const [ + SelectionRect(position: 0, bounds: Rect.fromLTRB(5.0, 0.0, 19.0, 14.0)), + SelectionRect(position: 1, bounds: Rect.fromLTRB(5.0, 14.0, 19.0, 28.0)), + SelectionRect(position: 2, bounds: Rect.fromLTRB(5.0, 28.0, 19.0, 42.0)), + SelectionRect(position: 3, bounds: Rect.fromLTRB(5.0, 42.0, 19.0, 56.0)), + // These 2 lines will be out of bounds. + // SelectionRect(position: 4, bounds: Rect.fromLTRB(5.0, 56.0, 19.0, 70.0)), + // SelectionRect(position: 5, bounds: Rect.fromLTRB(-23.0, 70.0, 19.0, 84.0)), + ]); + log.clear(); + + expect(scrollController.offset, 0); + + // Scrolling also triggers update. + scrollController.jumpTo(14); + await tester.pumpAndSettle(); + expect(log.single, const [ + SelectionRect(position: 0, bounds: Rect.fromLTRB(5.0, -14.0, 19.0, 0.0)), + SelectionRect(position: 1, bounds: Rect.fromLTRB(5.0, 0.0, 19.0, 14.0)), + SelectionRect(position: 2, bounds: Rect.fromLTRB(5.0, 14.0, 19.0, 28.0)), + SelectionRect(position: 3, bounds: Rect.fromLTRB(5.0, 28.0, 19.0, 42.0)), + SelectionRect(position: 4, bounds: Rect.fromLTRB(5.0, 42.0, 19.0, 56.0)), + // This line is skipped because it's below the bottom edge of the render + // object. + // SelectionRect(position: 5, bounds: Rect.fromLTRB(5.0, 56.0, 47.0, 70.0)), + ]); + log.clear(); + + // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. + }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); // [intended] + + testWidgets('selection rects are not sent if stylusHandwritingEnabled is false', (WidgetTester tester) async { + final List log = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { + log.add(methodCall); + return null; + }); + + controller.text = 'Text1'; + + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + EditableText( + key: ValueKey(controller.text), + controller: controller, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + stylusHandwritingEnabled: false, + ), + ], + ), + ), + ), + ); + await tester.showKeyboard(find.byKey(ValueKey(controller.text))); + + // There should be a new platform message updating the selection rects. + expect(log.where((MethodCall m) => m.method == 'TextInput.setSelectionRects').length, 0); + + // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. + }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); // [intended] + + testWidgets('selection rects sent even when character corners are outside of paintBounds', (WidgetTester tester) async { + final List> log = >[]; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) { + if (methodCall.method == 'TextInput.setSelectionRects') { + final List args = methodCall.arguments as List; + final List selectionRects = []; + for (final dynamic rect in args) { + selectionRects.add(SelectionRect( + position: (rect as List)[4] as int, + bounds: Rect.fromLTWH(rect[0] as double, rect[1] as double, rect[2] as double, rect[3] as double), + )); + } + log.add(selectionRects); + } + return null; + }); + + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + controller.text = 'Text1'; + + final GlobalKey editableTextKey = GlobalKey(); + + Future pumpEditableText({ double? width, double? height, TextAlign textAlign = TextAlign.start }) async { + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + width: width, + height: height, + child: EditableText( + controller: controller, + textAlign: textAlign, + scrollController: scrollController, + maxLines: null, + focusNode: focusNode, + cursorWidth: 0, + key: editableTextKey, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + ), + ), + ), + ), + ), + ); + } + + // Set height to 1 pixel less than full height. + await pumpEditableText(height: 13); + expect(log, isEmpty); + + // Scroll so that the top of each character is above the top of the renderEditable + // and the bottom of each character is below the bottom of the renderEditable. + final ViewportOffset offset = ViewportOffset.fixed(0.5); + addTearDown(offset.dispose); + editableTextKey.currentState!.renderEditable.offset = offset; + + await tester.showKeyboard(find.byType(EditableText)); + // We should get all the rects. + expect(log.single, const [ + SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, -0.5, 14.0, 13.5)), + SelectionRect(position: 1, bounds: Rect.fromLTRB(14.0, -0.5, 28.0, 13.5)), + SelectionRect(position: 2, bounds: Rect.fromLTRB(28.0, -0.5, 42.0, 13.5)), + SelectionRect(position: 3, bounds: Rect.fromLTRB(42.0, -0.5, 56.0, 13.5)), + SelectionRect(position: 4, bounds: Rect.fromLTRB(56.0, -0.5, 70.0, 13.5)) + ]); + log.clear(); + + // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. + }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); // [intended] + + // Regression test for https://github.com/flutter/flutter/issues/159259. + testWidgets('showToolbar does nothing and returns false when already shown during Scribble selection', (WidgetTester tester) async { + controller.text = 'Lorem ipsum dolor sit amet'; + final GlobalKey editableTextKey = GlobalKey(); + + await tester.pumpWidget( + MaterialApp( + home: EditableText( + key: editableTextKey, + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionHandleControls, + contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) { + return AdaptiveTextSelectionToolbar.editableText( + editableTextState: editableTextState, + ); + }, + ), + ), + ); + + expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); + + await tester.showKeyboard(find.byType(EditableText)); + + await tester.testTextInput.startScribbleInteraction(); + tester.testTextInput.updateEditingValue(TextEditingValue( + text: controller.text, + selection: const TextSelection(baseOffset: 3, extentOffset: 4), + )); + await tester.pumpAndSettle(); + + expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); + + expect(editableTextKey.currentState!.showToolbar(), isTrue); + await tester.pumpAndSettle(); + + expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); + + expect(editableTextKey.currentState!.showToolbar(), isFalse); + await tester.pump(); + + expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); + + await tester.pumpAndSettle(); + + expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); + + await tester.testTextInput.finishScribbleInteraction(); + }, + variant: const TargetPlatformVariant({ TargetPlatform.iOS }), + skip: kIsWeb, // [intended] + ); +} diff --git a/packages/flutter/test/widgets/editable_text_scribe_test.dart b/packages/flutter/test/widgets/editable_text_scribe_test.dart new file mode 100644 index 00000000000..7b4adb99aa0 --- /dev/null +++ b/packages/flutter/test/widgets/editable_text_scribe_test.dart @@ -0,0 +1,229 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:ui' show PointerDeviceKind; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); + + const TextStyle textStyle = TextStyle(); + const Color cursorColor = Color.fromARGB(0xFF, 0xFF, 0x00, 0x00); + final List calls = []; + bool isFeatureAvailableReturnValue = true; + late TextEditingController controller; + late FocusNode focusNode; + + setUp(() async { + calls.clear(); + isFeatureAvailableReturnValue = true; + binding.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.scribe, (MethodCall methodCall) { + calls.add(methodCall); + + return switch (methodCall.method) { + 'Scribe.isFeatureAvailable' => Future.value(isFeatureAvailableReturnValue), + 'Scribe.startStylusHandwriting' => Future.value(), + _=> throw FlutterError('Unexpected method call: ${methodCall.method}'), + }; + }); + + controller = TextEditingController( + text: 'Lorem ipsum dolor sit amet', + ); + focusNode = FocusNode(debugLabel: 'EditableText Node'); + }); + + tearDown(() { + controller.dispose(); + focusNode.dispose(); + }); + + Future pumpTextSelectionGestureDetectorBuilder( + WidgetTester tester, { + bool forcePressEnabled = true, + bool selectionEnabled = true, + }) async { + final GlobalKey editableTextKey = GlobalKey(); + final FakeTextSelectionGestureDetectorBuilderDelegate delegate = FakeTextSelectionGestureDetectorBuilderDelegate( + editableTextKey: editableTextKey, + forcePressEnabled: forcePressEnabled, + selectionEnabled: selectionEnabled, + ); + + final TextSelectionGestureDetectorBuilder provider = + TextSelectionGestureDetectorBuilder(delegate: delegate); + + await tester.pumpWidget( + MaterialApp( + home: provider.buildGestureDetector( + behavior: HitTestBehavior.translucent, + child: EditableText( + key: editableTextKey, + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + showSelectionHandles: true, + ), + ), + ), + ); + } + + testWidgets('when Scribe is available, starts handwriting on tap down', (WidgetTester tester) async { + isFeatureAvailableReturnValue = true; + + await pumpTextSelectionGestureDetectorBuilder(tester); + + expect(focusNode.hasFocus, isFalse); + + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.stylus, pointer: 1); + await gesture.down(tester.getCenter(find.byType(EditableText))); + + // Wait for the gesture arena. + await tester.pumpAndSettle(); + + expect(calls, hasLength(2)); + expect(calls.first.method, 'Scribe.isFeatureAvailable'); + expect(calls[1].method, 'Scribe.startStylusHandwriting'); + + await gesture.up(); + expect(focusNode.hasFocus, isTrue); + + // On web, let the browser handle handwriting input. + }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.android })); // [intended] + + testWidgets('when Scribe is unavailable, does not start handwriting on tap down', (WidgetTester tester) async { + isFeatureAvailableReturnValue = false; + + await pumpTextSelectionGestureDetectorBuilder(tester); + + expect(focusNode.hasFocus, isFalse); + + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.stylus, pointer: 1); + await gesture.down(tester.getCenter(find.byType(EditableText))); + + // Wait for the gesture arena. + await tester.pumpAndSettle(); + + expect(calls, hasLength(1)); + expect(calls.first.method, 'Scribe.isFeatureAvailable'); + + await gesture.up(); + }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.android })); // [intended] + + testWidgets('tap down event must be from a stylus in order to start handwriting', (WidgetTester tester) async { + isFeatureAvailableReturnValue = true; + + await pumpTextSelectionGestureDetectorBuilder(tester); + + expect(focusNode.hasFocus, isFalse); + + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + await gesture.down(tester.getCenter(find.byType(EditableText))); + + expect(calls, isEmpty); + + await gesture.up(); + }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.android })); // [intended] + + testWidgets('tap down event on a collapsed selection handle is handled by the handle and does not start handwriting', (WidgetTester tester) async { + isFeatureAvailableReturnValue = true; + + await pumpTextSelectionGestureDetectorBuilder(tester); + + expect(focusNode.hasFocus, isFalse); + expect(find.byType(CompositedTransformFollower), findsNothing); + + // Tap to show the collapsed selection handle. + final Offset fieldOffset = tester.getTopLeft(find.byType(EditableText)); + await tester.tapAt(fieldOffset + const Offset(20.0, 10.0)); + await tester.pump(); + expect(find.byType(CompositedTransformFollower), findsOneWidget); + + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.stylus, pointer: 1); + final Finder handleFinder = find.descendant( + of: find.byType(CompositedTransformFollower), + matching: find.byType(CustomPaint), + ); + await gesture.down(tester.getCenter(handleFinder)); + + // Wait for the gesture arena. + await tester.pumpAndSettle(); + + expect(calls, hasLength(0)); + expect(controller.selection.isCollapsed, isTrue); + final int cursorStart = controller.selection.start; + + // Dragging on top of the handle moves it like normal. + await gesture.moveBy(const Offset(20.0, 0.0)); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.start, greaterThan(cursorStart)); + expect(calls, hasLength(0)); + + await gesture.up(); + }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.android })); // [intended] + + testWidgets('tap down event on the end selection handle is handled by the handle and does not start handwriting', (WidgetTester tester) async { + isFeatureAvailableReturnValue = true; + + await pumpTextSelectionGestureDetectorBuilder(tester); + + expect(focusNode.hasFocus, isFalse); + expect(find.byType(CompositedTransformFollower), findsNothing); + + // Long press to select the first word and show both handles. + final Offset fieldOffset = tester.getTopLeft(find.byType(EditableText)); + await tester.longPressAt(fieldOffset + const Offset(20.0, 10.0)); + await tester.pump(); + expect(find.byType(CompositedTransformFollower), findsNWidgets(2)); + + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.stylus, pointer: 1); + final Finder endHandleFinder = find.descendant( + of: find.byType(CompositedTransformFollower).at(1), + matching: find.byType(CustomPaint), + ); + await gesture.down(tester.getCenter(endHandleFinder)); + + // Wait for the gesture arena. + await tester.pumpAndSettle(); + + expect(calls, isEmpty); + expect(controller.selection.isCollapsed, isFalse); + final TextSelection selectionStart = controller.selection; + + // Dragging on top of the handle extends selection like normal. + await gesture.moveBy(const Offset(20.0, 0.0)); + expect(controller.selection.isCollapsed, isFalse); + expect(controller.selection.start, equals(selectionStart.start)); + expect(controller.selection.end, greaterThan(selectionStart.end)); + expect(calls, isEmpty); + + await gesture.up(); + }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.android })); // [intended] +} + +class FakeTextSelectionGestureDetectorBuilderDelegate implements TextSelectionGestureDetectorBuilderDelegate { + FakeTextSelectionGestureDetectorBuilderDelegate({ + required this.editableTextKey, + required this.forcePressEnabled, + required this.selectionEnabled, + }); + + @override + final GlobalKey editableTextKey; + + @override + final bool forcePressEnabled; + + @override + final bool selectionEnabled; +} diff --git a/packages/flutter/test/widgets/editable_text_test.dart b/packages/flutter/test/widgets/editable_text_test.dart index 84e4d1923b9..77940709ef6 100644 --- a/packages/flutter/test/widgets/editable_text_test.dart +++ b/packages/flutter/test/widgets/editable_text_test.dart @@ -1094,88 +1094,6 @@ void main() { expect(focusNode.hasFocus, isFalse); }); - testWidgets('selection rects re-sent when refocused', (WidgetTester tester) async { - final List> log = >[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { - if (methodCall.method == 'TextInput.setSelectionRects') { - final List args = methodCall.arguments as List; - final List selectionRects = []; - for (final dynamic rect in args) { - selectionRects.add(SelectionRect( - position: (rect as List)[4] as int, - bounds: Rect.fromLTWH(rect[0] as double, rect[1] as double, rect[2] as double, rect[3] as double), - )); - } - log.add(selectionRects); - } - return null; - }); - - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - controller.text = 'Text1'; - - Future pumpEditableText({ double? width, double? height, TextAlign textAlign = TextAlign.start }) async { - await tester.pumpWidget( - MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - width: width, - height: height, - child: EditableText( - controller: controller, - textAlign: textAlign, - scrollController: scrollController, - maxLines: null, - focusNode: focusNode, - cursorWidth: 0, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - ), - ), - ), - ), - ), - ); - } - - const List expectedRects = [ - SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), - SelectionRect(position: 1, bounds: Rect.fromLTRB(14.0, 0.0, 28.0, 14.0)), - SelectionRect(position: 2, bounds: Rect.fromLTRB(28.0, 0.0, 42.0, 14.0)), - SelectionRect(position: 3, bounds: Rect.fromLTRB(42.0, 0.0, 56.0, 14.0)), - SelectionRect(position: 4, bounds: Rect.fromLTRB(56.0, 0.0, 70.0, 14.0)) - ]; - - await pumpEditableText(); - expect(log, isEmpty); - - await tester.showKeyboard(find.byType(EditableText)); - // First update. - expect(log.single, expectedRects); - log.clear(); - - await tester.pumpAndSettle(); - expect(log, isEmpty); - - focusNode.unfocus(); - await tester.pumpAndSettle(); - expect(log, isEmpty); - - focusNode.requestFocus(); - //await tester.showKeyboard(find.byType(EditableText)); - await tester.pumpAndSettle(); - // Should re-receive the same rects. - expect(log.single, expectedRects); - log.clear(); - - // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. - }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); // [intended] - testWidgets('EditableText does not derive selection color from DefaultSelectionStyle', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/103341. const TextEditingValue value = TextEditingValue( @@ -3027,327 +2945,6 @@ void main() { } }); - testWidgets('Selection changes during Scribble interaction should have the scribble cause', (WidgetTester tester) async { - controller.text = 'Lorem ipsum dolor sit amet'; - late SelectionChangedCause selectionCause; - - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { - if (cause != null) { - selectionCause = cause; - } - }, - ), - ), - ); - - await tester.showKeyboard(find.byType(EditableText)); - - // A normal selection update from the framework has 'keyboard' as the cause. - tester.testTextInput.updateEditingValue(TextEditingValue( - text: controller.text, - selection: const TextSelection(baseOffset: 2, extentOffset: 3), - )); - await tester.pumpAndSettle(); - - expect(selectionCause, SelectionChangedCause.keyboard); - - // A selection update during a scribble interaction has 'scribble' as the cause. - await tester.testTextInput.startScribbleInteraction(); - tester.testTextInput.updateEditingValue(TextEditingValue( - text: controller.text, - selection: const TextSelection(baseOffset: 3, extentOffset: 4), - )); - await tester.pumpAndSettle(); - - expect(selectionCause, SelectionChangedCause.scribble); - - await tester.testTextInput.finishScribbleInteraction(); - }, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); - - testWidgets('Requests focus and changes the selection when onScribbleFocus is called', (WidgetTester tester) async { - controller.text = 'Lorem ipsum dolor sit amet'; - late SelectionChangedCause selectionCause; - - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { - if (cause != null) { - selectionCause = cause; - } - }, - ), - ), - ); - - await tester.testTextInput.scribbleFocusElement(TextInput.scribbleClients.keys.first, Offset.zero); - - expect(focusNode.hasFocus, true); - expect(selectionCause, SelectionChangedCause.scribble); - - // On web, we should rely on the browser's implementation of Scribble, so the selection changed cause - // will never be SelectionChangedCause.scribble. - }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); // [intended] - - testWidgets('Declares itself for Scribble interaction if the bounds overlap the scribble rect and the widget is touchable', (WidgetTester tester) async { - controller.text = 'Lorem ipsum dolor sit amet'; - - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - ), - ), - ); - - final List elementEntry = [TextInput.scribbleClients.keys.first, 0.0, 0.0, 800.0, 600.0]; - - List> elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(0, 0, 1, 1)); - expect(elements.first, containsAll(elementEntry)); - - // Touch is outside the bounds of the widget. - elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(-1, -1, 1, 1)); - expect(elements.length, 0); - - // Widget is read only. - await tester.pumpWidget( - MaterialApp( - home: EditableText( - readOnly: true, - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - ), - ), - ); - - elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(0, 0, 1, 1)); - expect(elements.length, 0); - - // Widget is not touchable. - await tester.pumpWidget( - MaterialApp( - home: Stack(children: [ - EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - ), - Positioned( - left: 0, - top: 0, - right: 0, - bottom: 0, - child: Container(color: Colors.black), - ), - ], - ), - ), - ); - - elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(0, 0, 1, 1)); - expect(elements.length, 0); - - // Widget has scribble disabled. - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - scribbleEnabled: false, - ), - ), - ); - - elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(0, 0, 1, 1)); - expect(elements.length, 0); - - - // On web, we should rely on the browser's implementation of Scribble, so the engine will - // never request the scribble elements. - }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); // [intended] - - testWidgets('single line Scribble fields can show a horizontal placeholder', (WidgetTester tester) async { - controller.text = 'Lorem ipsum dolor sit amet'; - - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - ), - ), - ); - - await tester.showKeyboard(find.byType(EditableText)); - - tester.testTextInput.updateEditingValue(TextEditingValue( - text: controller.text, - selection: const TextSelection(baseOffset: 5, extentOffset: 5), - )); - await tester.pumpAndSettle(); - - await tester.testTextInput.scribbleInsertPlaceholder(); - await tester.pumpAndSettle(); - - TextSpan textSpan = findRenderEditable(tester).text! as TextSpan; - expect(textSpan.children!.length, 3); - expect((textSpan.children![0] as TextSpan).text, 'Lorem'); - expect(textSpan.children![1] is WidgetSpan, true); - expect((textSpan.children![2] as TextSpan).text, ' ipsum dolor sit amet'); - - await tester.testTextInput.scribbleRemovePlaceholder(); - await tester.pumpAndSettle(); - - textSpan = findRenderEditable(tester).text! as TextSpan; - expect(textSpan.children, null); - expect(textSpan.text, 'Lorem ipsum dolor sit amet'); - - // Widget has scribble disabled. - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - scribbleEnabled: false, - ), - ), - ); - - await tester.showKeyboard(find.byType(EditableText)); - - tester.testTextInput.updateEditingValue(TextEditingValue( - text: controller.text, - selection: const TextSelection(baseOffset: 5, extentOffset: 5), - )); - await tester.pumpAndSettle(); - - await tester.testTextInput.scribbleInsertPlaceholder(); - await tester.pumpAndSettle(); - - textSpan = findRenderEditable(tester).text! as TextSpan; - expect(textSpan.children, null); - expect(textSpan.text, 'Lorem ipsum dolor sit amet'); - - // On web, we should rely on the browser's implementation of Scribble, so the framework - // will not handle placeholders. - }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); // [intended] - - testWidgets('multiline Scribble fields can show a vertical placeholder', (WidgetTester tester) async { - controller.text = 'Lorem ipsum dolor sit amet'; - - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - maxLines: 2, - ), - ), - ); - - await tester.showKeyboard(find.byType(EditableText)); - - tester.testTextInput.updateEditingValue(TextEditingValue( - text: controller.text, - selection: const TextSelection(baseOffset: 5, extentOffset: 5), - )); - await tester.pumpAndSettle(); - - await tester.testTextInput.scribbleInsertPlaceholder(); - await tester.pumpAndSettle(); - - TextSpan textSpan = findRenderEditable(tester).text! as TextSpan; - expect(textSpan.children!.length, 4); - expect((textSpan.children![0] as TextSpan).text, 'Lorem'); - expect(textSpan.children![1] is WidgetSpan, true); - expect(textSpan.children![2] is WidgetSpan, true); - expect((textSpan.children![3] as TextSpan).text, ' ipsum dolor sit amet'); - - await tester.testTextInput.scribbleRemovePlaceholder(); - await tester.pumpAndSettle(); - - textSpan = findRenderEditable(tester).text! as TextSpan; - expect(textSpan.children, null); - expect(textSpan.text, 'Lorem ipsum dolor sit amet'); - - // Widget has scribble disabled. - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - maxLines: 2, - scribbleEnabled: false, - ), - ), - ); - - await tester.showKeyboard(find.byType(EditableText)); - - tester.testTextInput.updateEditingValue(TextEditingValue( - text: controller.text, - selection: const TextSelection(baseOffset: 5, extentOffset: 5), - )); - await tester.pumpAndSettle(); - - await tester.testTextInput.scribbleInsertPlaceholder(); - await tester.pumpAndSettle(); - - textSpan = findRenderEditable(tester).text! as TextSpan; - expect(textSpan.children, null); - expect(textSpan.text, 'Lorem ipsum dolor sit amet'); - - // On web, we should rely on the browser's implementation of Scribble, so the framework - // will not handle placeholders. - }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); // [intended] - testWidgets('Sends "updateConfig" when read-only flag is flipped', (WidgetTester tester) async { bool readOnly = true; late StateSetter setState; @@ -5593,261 +5190,6 @@ void main() { ); }); - testWidgets('selection rects are sent when they change', (WidgetTester tester) async { - addTearDown(tester.view.reset); - // Ensure selection rects are sent on iPhone (using SE 3rd gen size) - tester.view.physicalSize = const Size(750.0, 1334.0); - - final List> log = >[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) { - if (methodCall.method == 'TextInput.setSelectionRects') { - final List args = methodCall.arguments as List; - final List selectionRects = []; - for (final dynamic rect in args) { - selectionRects.add(SelectionRect( - position: (rect as List)[4] as int, - bounds: Rect.fromLTWH(rect[0] as double, rect[1] as double, rect[2] as double, rect[3] as double), - )); - } - log.add(selectionRects); - } - return null; - }); - - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - controller.text = 'Text1'; - - Future pumpEditableText({ double? width, double? height, TextAlign textAlign = TextAlign.start }) async { - await tester.pumpWidget( - MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - width: width, - height: height, - child: EditableText( - controller: controller, - textAlign: textAlign, - scrollController: scrollController, - maxLines: null, - focusNode: focusNode, - cursorWidth: 0, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - ), - ), - ), - ), - ), - ); - } - - await pumpEditableText(); - expect(log, isEmpty); - - await tester.showKeyboard(find.byType(EditableText)); - // First update. - expect(log.single, const [ - SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), - SelectionRect(position: 1, bounds: Rect.fromLTRB(14.0, 0.0, 28.0, 14.0)), - SelectionRect(position: 2, bounds: Rect.fromLTRB(28.0, 0.0, 42.0, 14.0)), - SelectionRect(position: 3, bounds: Rect.fromLTRB(42.0, 0.0, 56.0, 14.0)), - SelectionRect(position: 4, bounds: Rect.fromLTRB(56.0, 0.0, 70.0, 14.0)) - ]); - log.clear(); - - await tester.pumpAndSettle(); - expect(log, isEmpty); - - await pumpEditableText(); - expect(log, isEmpty); - - // Change the width such that each character occupies a line. - await pumpEditableText(width: 20); - expect(log.single, const [ - SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), - SelectionRect(position: 1, bounds: Rect.fromLTRB(0.0, 14.0, 14.0, 28.0)), - SelectionRect(position: 2, bounds: Rect.fromLTRB(0.0, 28.0, 14.0, 42.0)), - SelectionRect(position: 3, bounds: Rect.fromLTRB(0.0, 42.0, 14.0, 56.0)), - SelectionRect(position: 4, bounds: Rect.fromLTRB(0.0, 56.0, 14.0, 70.0)) - ]); - log.clear(); - - await tester.enterText(find.byType(EditableText), 'Text1👨‍👩‍👦'); - await tester.pump(); - expect(log.single, const [ - SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), - SelectionRect(position: 1, bounds: Rect.fromLTRB(0.0, 14.0, 14.0, 28.0)), - SelectionRect(position: 2, bounds: Rect.fromLTRB(0.0, 28.0, 14.0, 42.0)), - SelectionRect(position: 3, bounds: Rect.fromLTRB(0.0, 42.0, 14.0, 56.0)), - SelectionRect(position: 4, bounds: Rect.fromLTRB(0.0, 56.0, 14.0, 70.0)), - SelectionRect(position: 5, bounds: Rect.fromLTRB(0.0, 70.0, 42.0, 84.0)), - ]); - log.clear(); - - // The 4th line will be partially visible. - await pumpEditableText(width: 20, height: 45); - expect(log.single, const [ - SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), - SelectionRect(position: 1, bounds: Rect.fromLTRB(0.0, 14.0, 14.0, 28.0)), - SelectionRect(position: 2, bounds: Rect.fromLTRB(0.0, 28.0, 14.0, 42.0)), - SelectionRect(position: 3, bounds: Rect.fromLTRB(0.0, 42.0, 14.0, 56.0)), - ]); - log.clear(); - - await pumpEditableText(width: 20, height: 45, textAlign: TextAlign.right); - // This is 1px off from being completely right-aligned. The 1px width is - // reserved for caret. - expect(log.single, const [ - SelectionRect(position: 0, bounds: Rect.fromLTRB(5.0, 0.0, 19.0, 14.0)), - SelectionRect(position: 1, bounds: Rect.fromLTRB(5.0, 14.0, 19.0, 28.0)), - SelectionRect(position: 2, bounds: Rect.fromLTRB(5.0, 28.0, 19.0, 42.0)), - SelectionRect(position: 3, bounds: Rect.fromLTRB(5.0, 42.0, 19.0, 56.0)), - // These 2 lines will be out of bounds. - // SelectionRect(position: 4, bounds: Rect.fromLTRB(5.0, 56.0, 19.0, 70.0)), - // SelectionRect(position: 5, bounds: Rect.fromLTRB(-23.0, 70.0, 19.0, 84.0)), - ]); - log.clear(); - - expect(scrollController.offset, 0); - - // Scrolling also triggers update. - scrollController.jumpTo(14); - await tester.pumpAndSettle(); - expect(log.single, const [ - SelectionRect(position: 0, bounds: Rect.fromLTRB(5.0, -14.0, 19.0, 0.0)), - SelectionRect(position: 1, bounds: Rect.fromLTRB(5.0, 0.0, 19.0, 14.0)), - SelectionRect(position: 2, bounds: Rect.fromLTRB(5.0, 14.0, 19.0, 28.0)), - SelectionRect(position: 3, bounds: Rect.fromLTRB(5.0, 28.0, 19.0, 42.0)), - SelectionRect(position: 4, bounds: Rect.fromLTRB(5.0, 42.0, 19.0, 56.0)), - // This line is skipped because it's below the bottom edge of the render - // object. - // SelectionRect(position: 5, bounds: Rect.fromLTRB(5.0, 56.0, 47.0, 70.0)), - ]); - log.clear(); - - // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. - }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); // [intended] - - testWidgets('selection rects are not sent if scribbleEnabled is false', (WidgetTester tester) async { - final List log = []; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); - - controller.text = 'Text1'; - - await tester.pumpWidget( - MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - EditableText( - key: ValueKey(controller.text), - controller: controller, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - scribbleEnabled: false, - ), - ], - ), - ), - ), - ); - await tester.showKeyboard(find.byKey(ValueKey(controller.text))); - - // There should be a new platform message updating the selection rects. - expect(log.where((MethodCall m) => m.method == 'TextInput.setSelectionRects').length, 0); - - // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. - }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); // [intended] - - testWidgets('selection rects sent even when character corners are outside of paintBounds', (WidgetTester tester) async { - final List> log = >[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) { - if (methodCall.method == 'TextInput.setSelectionRects') { - final List args = methodCall.arguments as List; - final List selectionRects = []; - for (final dynamic rect in args) { - selectionRects.add(SelectionRect( - position: (rect as List)[4] as int, - bounds: Rect.fromLTWH(rect[0] as double, rect[1] as double, rect[2] as double, rect[3] as double), - )); - } - log.add(selectionRects); - } - return null; - }); - - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - controller.text = 'Text1'; - - final GlobalKey editableTextKey = GlobalKey(); - - Future pumpEditableText({ double? width, double? height, TextAlign textAlign = TextAlign.start }) async { - await tester.pumpWidget( - MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - width: width, - height: height, - child: EditableText( - controller: controller, - textAlign: textAlign, - scrollController: scrollController, - maxLines: null, - focusNode: focusNode, - cursorWidth: 0, - key: editableTextKey, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - ), - ), - ), - ), - ), - ); - } - - // Set height to 1 pixel less than full height. - await pumpEditableText(height: 13); - expect(log, isEmpty); - - // Scroll so that the top of each character is above the top of the renderEditable - // and the bottom of each character is below the bottom of the renderEditable. - final ViewportOffset offset = ViewportOffset.fixed(0.5); - addTearDown(offset.dispose); - editableTextKey.currentState!.renderEditable.offset = offset; - - await tester.showKeyboard(find.byType(EditableText)); - // We should get all the rects. - expect(log.single, const [ - SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, -0.5, 14.0, 13.5)), - SelectionRect(position: 1, bounds: Rect.fromLTRB(14.0, -0.5, 28.0, 13.5)), - SelectionRect(position: 2, bounds: Rect.fromLTRB(28.0, -0.5, 42.0, 13.5)), - SelectionRect(position: 3, bounds: Rect.fromLTRB(42.0, -0.5, 56.0, 13.5)), - SelectionRect(position: 4, bounds: Rect.fromLTRB(56.0, -0.5, 70.0, 13.5)) - ]); - log.clear(); - - // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. - }, skip: kIsWeb, variant: const TargetPlatformVariant({ TargetPlatform.iOS })); // [intended] - testWidgets('text styling info is sent on show keyboard', (WidgetTester tester) async { final List log = []; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { @@ -13502,7 +12844,7 @@ void main() { selection: TextSelection.collapsed(offset: textAC.length), ); - bool isDeskop() { + bool isDesktop() { return debugDefaultTargetPlatformOverride == TargetPlatform.macOS || debugDefaultTargetPlatformOverride == TargetPlatform.windows || debugDefaultTargetPlatformOverride == TargetPlatform.linux; @@ -13690,7 +13032,7 @@ void main() { focusNode.requestFocus(); await tester.pump(); await waitForThrottling(tester); - expect(controller.value, isDeskop() ? textASelected : textACollapsedAtEnd); + expect(controller.value, isDesktop() ? textASelected : textACollapsedAtEnd); // Insert some text. await tester.enterText(find.byType(EditableText), textAB); @@ -13699,7 +13041,7 @@ void main() { // Undo the insertion without waiting for the throttling delay. await sendUndo(tester); expect(controller.value.selection.isValid, true); - expect(controller.value, isDeskop() ? textASelected : textACollapsedAtEnd); + expect(controller.value, isDesktop() ? textASelected : textACollapsedAtEnd); // On web, these keyboard shortcuts are handled by the browser. }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] @@ -13714,7 +13056,7 @@ void main() { await tester.pump(); await sendUndo(tester); await waitForThrottling(tester); - expect(controller.value, isDeskop() ? textASelected : textACollapsedAtEnd); + expect(controller.value, isDesktop() ? textASelected : textACollapsedAtEnd); // Insert some text. await tester.enterText(find.byType(EditableText), textAB); @@ -13724,7 +13066,7 @@ void main() { await sendUndo(tester); // Initial text should have been recorded and restored. - expect(controller.value, isDeskop() ? textASelected : textACollapsedAtEnd); + expect(controller.value, isDesktop() ? textASelected : textACollapsedAtEnd); // On web, these keyboard shortcuts are handled by the browser. }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] @@ -17618,7 +16960,7 @@ void main() { ), ); await tester.pumpWidget(widget); - await tester.showKeyboard(find.byType(EditableText)); + await tester.showKeyboard(find.byType(EditableText, skipOffstage: false)); await tester.pumpAndSettle(); expect(scrollController.offset, 75.0); }); @@ -17870,6 +17212,51 @@ void main() { expect(tester.takeException(), isNull); }); + + // Regression test for https://github.com/flutter/flutter/issues/159259. + testWidgets('showToolbar does nothing and returns false when already shown', (WidgetTester tester) async { + controller.text = 'Lorem ipsum dolor sit amet'; + final GlobalKey editableTextKey = GlobalKey(); + + await tester.pumpWidget( + MaterialApp( + home: EditableText( + key: editableTextKey, + autofocus: true, + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionHandleControls, + contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) { + return AdaptiveTextSelectionToolbar.editableText( + editableTextState: editableTextState, + ); + }, + ), + ), + ); + + expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); + + expect(editableTextKey.currentState!.showToolbar(), isTrue); + await tester.pumpAndSettle(); + + expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); + + expect(editableTextKey.currentState!.showToolbar(), isFalse); + await tester.pump(); + + expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); + + await tester.pumpAndSettle(); + + expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); + }, + variant: const TargetPlatformVariant({ TargetPlatform.iOS }), + skip: kIsWeb, // [intended] + ); } class UnsettableController extends TextEditingController { diff --git a/packages/flutter/test/widgets/fade_transition_test.dart b/packages/flutter/test/widgets/fade_transition_test.dart index b606c95137c..4f8136cf6f9 100644 --- a/packages/flutter/test/widgets/fade_transition_test.dart +++ b/packages/flutter/test/widgets/fade_transition_test.dart @@ -10,7 +10,7 @@ void main() { testWidgets('FadeTransition', (WidgetTester tester) async { final DebugPrintCallback oldPrint = debugPrint; final List log = []; - debugPrint = (String? message, { int? wrapWidth }) { + debugPrint = (String? message, {int? wrapWidth}) { log.add(message!); }; debugPrintBuildScope = true; @@ -33,4 +33,24 @@ void main() { debugPrint = oldPrint; debugPrintBuildScope = false; }); + + // Regression test for https://github.com/flutter/flutter/issues/157312 + testWidgets('No exception when calling markNeedsPaint during opacity changes', (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + final AnimationController controller = AnimationController( + vsync: const TestVSync(), + value: 1, + duration: const Duration(seconds: 2), + ); + addTearDown(controller.dispose); + await tester.pumpWidget(FadeTransition( + opacity: controller, + child: Placeholder(key: key), + )); + controller.value = 0.5; + key.currentContext?.findRenderObject()?.markNeedsPaint(); + controller.value = 0; + await tester.pump(); + expect(tester.takeException(), isNull); + }); } diff --git a/packages/flutter/test/widgets/form_test.dart b/packages/flutter/test/widgets/form_test.dart index 9785d7c28d2..e4602172137 100644 --- a/packages/flutter/test/widgets/form_test.dart +++ b/packages/flutter/test/widgets/form_test.dart @@ -139,44 +139,52 @@ void main() { await checkErrorText(''); }); - testWidgets('Should announce error text when validate returns error', (WidgetTester tester) async { - final GlobalKey formKey = GlobalKey(); - await tester.pumpWidget( - MaterialApp( - home: MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: Material( - child: Form( - key: formKey, - child: TextFormField( - validator: (_)=> 'error', - ), + testWidgets('Should announce only the first error message when validate returns errors', (WidgetTester tester) async { + final GlobalKey formKey = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + home: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Material( + child: Form( + key: formKey, + child: Column( + children: [ + TextFormField( + validator: (_) => 'First error message', + ), + TextFormField( + validator: (_) => 'Second error message', + ), + ], ), ), ), ), ), ), - ); - formKey.currentState!.reset(); - await tester.enterText(find.byType(TextFormField), ''); - await tester.pump(); + ), + ); + formKey.currentState!.reset(); + await tester.enterText(find.byType(TextFormField).first, ''); + await tester.pump(); - // Manually validate. - expect(find.text('error'), findsNothing); - formKey.currentState!.validate(); - await tester.pump(); - expect(find.text('error'), findsOneWidget); + // Manually validate. + expect(find.text('First error message'), findsNothing); + expect(find.text('Second error message'), findsNothing); + formKey.currentState!.validate(); + await tester.pump(); + expect(find.text('First error message'), findsOneWidget); + expect(find.text('Second error message'), findsOneWidget); - final CapturedAccessibilityAnnouncement announcement = tester.takeAnnouncements().single; - expect(announcement.message, 'error'); - expect(announcement.textDirection, TextDirection.ltr); - expect(announcement.assertiveness, Assertiveness.assertive); - - }); + final CapturedAccessibilityAnnouncement announcement = tester.takeAnnouncements().single; + expect(announcement.message, 'First error message'); + expect(announcement.textDirection, TextDirection.ltr); + expect(announcement.assertiveness, Assertiveness.assertive); +}); testWidgets('isValid returns true when a field is valid', (WidgetTester tester) async { final GlobalKey> fieldKey1 = GlobalKey>(); @@ -1457,4 +1465,93 @@ void main() { expect(focusNode2.hasFocus, isTrue); }); + + testWidgets('AutovalidateMode.always should validate on second build', (WidgetTester tester) async { + String errorText(String? value) => '$value/error'; + + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(), + home: Center( + child: Form( + autovalidateMode: AutovalidateMode.always, + child: Material( + child: Column( + children: [ + TextFormField( + initialValue: 'foo', + validator: errorText, + ), + TextFormField( + initialValue: 'bar', + validator: errorText, + ), + ], + ), + ), + ), + ), + ), + ); + + // The validation happens in a post frame callback, so the error + // doesn't show up until the second frame. + expect(find.text(errorText('foo')), findsNothing); + expect(find.text(errorText('bar')), findsNothing); + + await tester.pump(); + + // The error shows up on the second frame. + expect(find.text(errorText('foo')), findsOneWidget); + expect(find.text(errorText('bar')), findsOneWidget); + }); + + testWidgets('AutovalidateMode.onUnfocus should validate all fields manually with FormState', (WidgetTester tester) async { + final GlobalKey formKey = GlobalKey(); + const Key fieldKey = Key('form field'); + String errorText(String? value) => '$value/error'; + + await tester.pumpWidget( + MaterialApp( + home: Center( + child: Form( + key: formKey, + autovalidateMode: AutovalidateMode.onUnfocus, + child: Material( + child: Column( + children: [ + TextFormField( + key: fieldKey, + initialValue: 'foo', + validator: errorText, + ), + TextFormField( + initialValue: 'bar', + validator: errorText, + ), + ], + ), + ), + ), + ), + ), + ); + + + // Focus on the first field. + await tester.tap(find.byKey(fieldKey)); + await tester.pump(); + + // Check no error messages are displayed initially. + expect(find.text('foo/error'), findsNothing); + expect(find.text('bar/error'), findsNothing); + + // Validate all fields manually using FormState. + expect(formKey.currentState!.validate(), isFalse); + await tester.pump(); + + // Check error messages are displayed. + expect(find.text('foo/error'), findsOneWidget); + expect(find.text('bar/error'), findsOneWidget); + }); } diff --git a/packages/flutter/test/widgets/framework_test.dart b/packages/flutter/test/widgets/framework_test.dart index b1e7086f1d5..ce74e64fc5a 100644 --- a/packages/flutter/test/widgets/framework_test.dart +++ b/packages/flutter/test/widgets/framework_test.dart @@ -2424,11 +2424,11 @@ class _DummyMultiChildWidget extends Widget { final List children; @override - Element createElement() => _DummyMuitiChildElement(this); + Element createElement() => _DummyMultiChildElement(this); } -class _DummyMuitiChildElement extends Element { - _DummyMuitiChildElement(super.widget); +class _DummyMultiChildElement extends Element { + _DummyMultiChildElement(super.widget); @override bool get debugDoingBuild => throw UnimplementedError(); diff --git a/packages/flutter/test/widgets/list_view_semantics_test.dart b/packages/flutter/test/widgets/list_view_semantics_test.dart index 88727fff1f4..4841fa9b4c2 100644 --- a/packages/flutter/test/widgets/list_view_semantics_test.dart +++ b/packages/flutter/test/widgets/list_view_semantics_test.dart @@ -35,12 +35,12 @@ void main() { ), ); - expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollUp])); + expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollUp, SemanticsAction.scrollToOffset])); // Jump to the end. controller.jumpTo(itemCount * itemHeight); await tester.pumpAndSettle(); - expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollDown])); + expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollDown, SemanticsAction.scrollToOffset])); semantics.dispose(); }); @@ -67,12 +67,12 @@ void main() { ), ); - expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollDown])); + expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollDown, SemanticsAction.scrollToOffset])); // Jump to the end. controller.jumpTo(itemCount * itemHeight); await tester.pumpAndSettle(); - expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollUp])); + expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollUp, SemanticsAction.scrollToOffset])); semantics.dispose(); }); @@ -99,12 +99,12 @@ void main() { ), ); - expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollLeft])); + expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollLeft, SemanticsAction.scrollToOffset])); // Jump to the end. controller.jumpTo(itemCount * itemHeight); await tester.pumpAndSettle(); - expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollRight])); + expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollRight, SemanticsAction.scrollToOffset])); semantics.dispose(); }); @@ -132,12 +132,12 @@ void main() { ), ); - expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollRight])); + expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollRight, SemanticsAction.scrollToOffset])); // Jump to the end. controller.jumpTo(itemCount * itemHeight); await tester.pumpAndSettle(); - expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollLeft])); + expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollLeft, SemanticsAction.scrollToOffset])); semantics.dispose(); }); diff --git a/packages/flutter/test/widgets/reorderable_list_test.dart b/packages/flutter/test/widgets/reorderable_list_test.dart index b3d1ab90d4c..cce29834b94 100644 --- a/packages/flutter/test/widgets/reorderable_list_test.dart +++ b/packages/flutter/test/widgets/reorderable_list_test.dart @@ -1677,6 +1677,51 @@ void main() { await drag.up(); await tester.pumpAndSettle(); }); + + testWidgets('DragBoundary defines the boundary for ReorderableList.', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Container( + margin: const EdgeInsets.only(top: 100), + height: 300, + child: DragBoundary( + child: CustomScrollView( + slivers: [ + SliverReorderableList( + itemBuilder: (BuildContext context, int index) { + return ReorderableDragStartListener( + key: ValueKey(index), + index: index, + child: Text('$index'), + ); + }, + itemCount: 5, + onReorder: (int fromIndex, int toIndex) {}, + ), + ], + ) + ), + ), + ), + ), + ); + TestGesture drag = await tester.startGesture(tester.getCenter(find.text('0'))); + await tester.pump(kLongPressTimeout); + await drag.moveBy(const Offset(0, -400)); + await tester.pumpAndSettle(); + expect(tester.getTopLeft(find.text('0')), const Offset(0, 100)); + await drag.up(); + await tester.pumpAndSettle(); + + drag = await tester.startGesture(tester.getCenter(find.text('0'))); + await tester.pump(kLongPressTimeout); + await drag.moveBy(const Offset(0, 800)); + await tester.pumpAndSettle(); + expect(tester.getBottomLeft(find.text('0')), const Offset(0, 400)); + await drag.up(); + await tester.pumpAndSettle(); + }); } class TestList extends StatelessWidget { diff --git a/packages/flutter/test/widgets/routes_test.dart b/packages/flutter/test/widgets/routes_test.dart index 461088284ca..dbd83571c5c 100644 --- a/packages/flutter/test/widgets/routes_test.dart +++ b/packages/flutter/test/widgets/routes_test.dart @@ -7,6 +7,7 @@ import 'dart:ui'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/physics.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -1473,6 +1474,160 @@ void main() { await tester.pump(const Duration(milliseconds: 1)); expect(find.byKey(containerKey), findsNothing); }); + + testWidgets('Routes can use simulation and ignore durations', (WidgetTester tester) async { + final GlobalKey containerKey = GlobalKey(); + + await tester.pumpWidget(MaterialApp( + onGenerateRoute: (RouteSettings settings) { + return MaterialPageRoute( + builder: (BuildContext context) { + return ElevatedButton( + onPressed: () { + Navigator.of(context).push( + _SimulationRoute( + simulationBuilder: ({required double current, required bool forward}) { + // This simulation takes 1.0 second to transit. + return GravitySimulation( + 0, // Acceleration + 0.0, // Start position + 1.0, // End distance + 1.0); // Init velocity + }, + // Set an extremely long duration so that the route must ignore these + // durations to proceed. + transitionDuration: const Duration(days: 1), + reverseTransitionDuration: const Duration(days: 1), + pageBuilder: (_, Animation animation, Animation secondaryAnimation) { + return Container( + key: containerKey, + color: Colors.green, + ); + }, + transitionBuilder: (BuildContext context, Animation animation, Widget child) { + return child; + } + ), + ); + }, + child: const Text('Open page'), + ); + }, + ); + }, + )); + + // Open the new route. + await tester.tap(find.byType(ElevatedButton)); + await tester.pumpAndSettle(); + expect(find.text('Open page'), findsNothing); + expect(find.byKey(containerKey), findsOneWidget); + + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byKey(containerKey), findsOneWidget); + + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byKey(containerKey), findsOneWidget); + + await tester.pumpAndSettle(); + + // Pop the new route. + tester.state(find.byType(Navigator)).pop(); + await tester.pump(); + expect(find.byKey(containerKey), findsOneWidget); + + // Container should be present halfway through the transition. + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byKey(containerKey), findsOneWidget); + + // Container should be present at the very end of the transition. + await tester.pump(const Duration(milliseconds: 490)); + expect(find.byKey(containerKey), findsOneWidget); + + // Container have transitioned out after 500ms. + await tester.pump(const Duration(milliseconds: 200)); + expect(find.byKey(containerKey), findsNothing); + }); + + testWidgets('Routes can use simulation value', (WidgetTester tester) async { + final GlobalKey containerKey = GlobalKey(); + + await tester.pumpWidget(MaterialApp( + onGenerateRoute: (RouteSettings settings) { + return MaterialPageRoute( + builder: (BuildContext context) { + return ElevatedButton( + onPressed: () { + Navigator.of(context).push( + _SimulationRoute( + simulationBuilder: ({required double current, required bool forward}) { + return _ConstantVelocitySimulation(forward: forward, speed: 1.0); // Init velocity + }, + transitionDuration: const Duration(days: 1), + reverseTransitionDuration: const Duration(days: 1), + pageBuilder: (_, Animation animation, Animation secondaryAnimation) { + return Container( + key: containerKey, + color: Colors.green, + ); + }, + transitionBuilder: (BuildContext context, Animation animation, Widget child) { + return FractionalTranslation( + translation: Tween(begin: const Offset(0.0, 1.0), end: Offset.zero) + .evaluate(animation), + child: child, // child is the value returned by pageBuilder + ); + } + ), + ); + }, + child: const Text('Open page'), + ); + }, + ); + }, + )); + + // Open the new route. + await tester.tap(find.byType(ElevatedButton)); + // Must pump two frames for the animation to take effect. The first pump + // starts the animation, the 2nd pump makes the wiget appear. + await tester.pump(); + await tester.pump(); + expect(find.byKey(containerKey), findsOneWidget); + expect(tester.getTopLeft(find.byKey(containerKey)), const Offset(0, 600)); + + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byKey(containerKey), findsOneWidget); + expect(tester.getTopLeft(find.byKey(containerKey)), const Offset(0, 300)); + + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byKey(containerKey), findsOneWidget); + expect(tester.getTopLeft(find.byKey(containerKey)), Offset.zero); + + await tester.pumpAndSettle(); + + // Pop the new route. + tester.state(find.byType(Navigator)).pop(); + await tester.pump(); + await tester.pump(); + expect(find.byKey(containerKey), findsOneWidget); + expect(tester.getTopLeft(find.byKey(containerKey)), Offset.zero); + + // Container should be present halfway through the transition. + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byKey(containerKey), findsOneWidget); + expect(tester.getTopLeft(find.byKey(containerKey)), const Offset(0, 300)); + + // Container should be present at the very end of the transition. + await tester.pump(const Duration(milliseconds: 490)); + expect(find.byKey(containerKey), findsOneWidget); + expect(tester.getTopLeft(find.byKey(containerKey)), const Offset(0, 594)); + + // Container have transitioned out after 500ms. + await tester.pump(const Duration(milliseconds: 200)); + expect(find.byKey(containerKey), findsNothing); + }); }); group('ModalRoute', () { @@ -2600,6 +2755,7 @@ class WidgetWithNoLocalHistoryState extends State { } } +@pragma('vm:entry-point') class _RestorableDialogTestWidget extends StatelessWidget { const _RestorableDialogTestWidget(); @@ -2630,3 +2786,58 @@ class _RestorableDialogTestWidget extends StatelessWidget { ); } } + +typedef _SimulationBuilder = Simulation Function({ required double current, required bool forward }); +typedef _TransitionBuilder = Widget Function(BuildContext context, Animation animation, Widget child); + +// A route that is driven by a simulation. +class _SimulationRoute extends PageRouteBuilder { + _SimulationRoute({ + required this.simulationBuilder, + required this.transitionBuilder, + required super.pageBuilder, + super.transitionDuration = const Duration(milliseconds: 300), + super.reverseTransitionDuration = const Duration(milliseconds: 300), + }); + + final _SimulationBuilder simulationBuilder; + final _TransitionBuilder transitionBuilder; + + @override + Simulation createSimulation({ required bool forward }) { + return simulationBuilder(current: controller!.value, forward: forward); + } + + @override + Widget buildTransitions(BuildContext context, Animation animation, Animation secondaryAnimation, Widget child) { + return transitionBuilder(context, animation, child); + } +} + +// A simulation that progresses at a constant speed. +// +// If `forward` is true, the simulation goes from 0 to 1, otherwise from 1 to 0. +class _ConstantVelocitySimulation extends Simulation { + _ConstantVelocitySimulation({ + required this.forward, + required this.speed, + }) : _start = forward ? 0.0 : 1.0; + + final bool forward; + final double speed; + final double _start; + + @override + double x(double time) { + return _start + time * dx(time); + } + + @override + double dx(double time) => forward ? speed : -speed; + + @override + bool isDone(double time) { + final double nowX = x(time); + return nowX > 1.0 || nowX < 0; + } +} diff --git a/packages/flutter/test/widgets/scrollable_helpers_test.dart b/packages/flutter/test/widgets/scrollable_helpers_test.dart index e057a4292b4..b110e449290 100644 --- a/packages/flutter/test/widgets/scrollable_helpers_test.dart +++ b/packages/flutter/test/widgets/scrollable_helpers_test.dart @@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -11,6 +12,21 @@ final LogicalKeyboardKey modifierKey = defaultTargetPlatform == TargetPlatform.m ? LogicalKeyboardKey.metaLeft : LogicalKeyboardKey.controlLeft; +class _NoNotificationContextScrollable extends Scrollable { + const _NoNotificationContextScrollable({ + super.controller, + required super.viewportBuilder, + }); + + @override + ScrollableState createState() => _NoNotificationContextScrollableState(); +} + +class _NoNotificationContextScrollableState extends ScrollableState { + @override + BuildContext? get notificationContext => null; +} + void main() { group('ScrollableDetails', (){ test('copyWith / == / hashCode', () { @@ -590,4 +606,73 @@ void main() { expect(find.text('The cape as red as blood'), findsOneWidget); expect(find.text('The hair as yellow as corn'), findsOneWidget); }); + + // Regression test for https://github.com/flutter/flutter/issues/158063. + testWidgets('Invoking a ScrollAction when notificationContext is null does not cause an exception.', (WidgetTester tester) async { + const List keysWithModifier = [ + LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowUp, + ]; + const List keys = [ + ...keysWithModifier, + LogicalKeyboardKey.pageDown, LogicalKeyboardKey.pageUp, + ]; + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.fuchsia), + home: PrimaryScrollController( + controller: controller, + child: Focus( + autofocus: true, + child: _NoNotificationContextScrollable( + controller: controller, + viewportBuilder: (BuildContext context, ViewportOffset offset) => Viewport( + offset: offset, + slivers: List.generate( + 20, + (int index) => SliverToBoxAdapter( + child: SizedBox( + key: ValueKey('Box $index'), + height: 50.0, + ), + ), + ), + ), + ), + ), + ), + ), + ); + + // Verify the initial scroll offset. + await tester.pumpAndSettle(); + expect(controller.position.pixels, equals(0.0)); + expect( + tester.getRect(find.byKey(const ValueKey('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), + ); + + for (final LogicalKeyboardKey key in keys) { + // The default web shortcuts do not use a modifier key for ScrollActions. + if (!kIsWeb && keysWithModifier.contains(key)) { + await tester.sendKeyDownEvent(modifierKey); + } + + await tester.sendKeyEvent(key); + expect(tester.takeException(), isNull); + + if (!kIsWeb && keysWithModifier.contains(key)) { + await tester.sendKeyUpEvent(modifierKey); + } + + // No scrollable is found, so the scroll position should not change. + await tester.pumpAndSettle(); + expect(controller.position.pixels, equals(0.0)); + expect( + tester.getRect(find.byKey(const ValueKey('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), + ); + } + }, variant: KeySimulatorTransitModeVariant.all()); } diff --git a/packages/flutter/test/widgets/scrollable_semantics_test.dart b/packages/flutter/test/widgets/scrollable_semantics_test.dart index c8486ff97ad..fdcc0e532b9 100644 --- a/packages/flutter/test/widgets/scrollable_semantics_test.dart +++ b/packages/flutter/test/widgets/scrollable_semantics_test.dart @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart' show DragStartBehavior; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; @@ -25,23 +26,99 @@ void main() { ), ); - expect(semantics,includesNodeWith(actions: [SemanticsAction.scrollUp])); + expect(semantics,includesNodeWith(actions: [SemanticsAction.scrollUp, SemanticsAction.scrollToOffset])); await flingUp(tester); - expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollUp, SemanticsAction.scrollDown])); + expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollUp, SemanticsAction.scrollDown, SemanticsAction.scrollToOffset])); await flingDown(tester, repetitions: 2); - expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollUp])); + expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollUp, SemanticsAction.scrollToOffset])); await flingUp(tester, repetitions: 5); - expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollDown])); + expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollDown, SemanticsAction.scrollToOffset])); await flingDown(tester); - expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollUp, SemanticsAction.scrollDown])); + expect(semantics, includesNodeWith(actions: [SemanticsAction.scrollUp, SemanticsAction.scrollDown, SemanticsAction.scrollToOffset])); semantics.dispose(); }); + testWidgets('Vertical scrollable responds to scrollToOffset', (WidgetTester tester) async { + semantics = SemanticsTester(tester); + final ScrollController controller = ScrollController(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView( + controller: controller, + children: List.generate(60, (int i) => Text('$i')), + ), + ), + ); + final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!; + final int scrollableId = semantics.nodesWith(actions: [SemanticsAction.scrollUp, SemanticsAction.scrollToOffset]).single.id; + + assert(controller.offset == 0); + semanticsOwner.performAction(scrollableId, SemanticsAction.scrollToOffset, Float64List.fromList([123.0, 456.0])); + expect(controller.offset, 456.0); + controller.dispose(); + semantics.dispose(); + }); + + testWidgets('Horizontal scrollable responds to scrollToOffset', (WidgetTester tester) async { + semantics = SemanticsTester(tester); + final ScrollController controller = ScrollController(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView( + controller: controller, + scrollDirection: Axis.horizontal, + children: List.generate(60, (int i) => Text('$i')), + ), + ), + ); + final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!; + final int scrollableId = semantics.nodesWith(actions: [SemanticsAction.scrollLeft, SemanticsAction.scrollToOffset]).single.id; + + assert(controller.offset == 0); + semanticsOwner.performAction(scrollableId, SemanticsAction.scrollToOffset, Float64List.fromList([123.0, 456.0])); + expect(controller.offset, 123.0); + controller.dispose(); + semantics.dispose(); + }); + + testWidgets('Unscrollable scrollable does not respond to scrollToOffset', (WidgetTester tester) async { + semantics = SemanticsTester(tester); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView( + children: List.generate(3, (int i) => Text('$i')), + ), + ), + ); + expect(semantics.nodesWith(actions: [SemanticsAction.scrollUp, SemanticsAction.scrollToOffset]), isEmpty); + semantics.dispose(); + }); + + testWidgets('scrollToOffset respects implicit scrolling configuration', (WidgetTester tester) async { + semantics = SemanticsTester(tester); + final ScrollPhysics physics = _NoImplicitScrollingScrollPhysics(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView( + physics: physics, + children: List.generate(60, (int i) => Text('$i')), + ), + ), + ); + expect(semantics.nodesWith(actions: [SemanticsAction.scrollUp, SemanticsAction.scrollToOffset]), isEmpty); + semantics.dispose(); + }); + + testWidgets('showOnScreen works in scrollable', (WidgetTester tester) async { semantics = SemanticsTester(tester); // enables semantics tree generation @@ -227,6 +304,7 @@ void main() { scrollExtentMax: 520.0, actions: [ SemanticsAction.scrollUp, + SemanticsAction.scrollToOffset, ], )); @@ -239,6 +317,7 @@ void main() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], )); @@ -250,6 +329,7 @@ void main() { scrollExtentMax: 520.0, actions: [ SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], )); @@ -276,6 +356,7 @@ void main() { scrollExtentMax: double.infinity, actions: [ SemanticsAction.scrollUp, + SemanticsAction.scrollToOffset, ], )); @@ -288,6 +369,7 @@ void main() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], )); @@ -300,6 +382,7 @@ void main() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], )); @@ -354,7 +437,7 @@ void main() { flags: [ SemanticsFlag.hasImplicitScrolling, ], - actions: [SemanticsAction.scrollUp], + actions: [SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], children: [ TestSemantics( label: r'item 0', @@ -614,7 +697,7 @@ void main() { ), ); - final SemanticsNode rootScrollNode = semantics.nodesWith(actions: [SemanticsAction.scrollUp]).single; + final SemanticsNode rootScrollNode = semantics.nodesWith(actions: [SemanticsAction.scrollUp, SemanticsAction.scrollToOffset]).single; final SemanticsNode innerListPane = semantics.nodesWith(ancestor: rootScrollNode, scrollExtentMax: 0).single; final SemanticsNode outerListPane = innerListPane.parent!; final List hiddenNodes = semantics.nodesWith(flags: [SemanticsFlag.isHidden]).toList(); @@ -664,3 +747,11 @@ Rect nodeGlobalRect(SemanticsNode node) { } return MatrixUtils.transformRect(globalTransform, node.rect); } + +class _NoImplicitScrollingScrollPhysics extends ScrollPhysics { + @override + bool get allowImplicitScrolling => false; + + @override + ScrollPhysics applyTo(ScrollPhysics? ancestor) => this; +} diff --git a/packages/flutter/test/widgets/scrollable_semantics_traversal_order_test.dart b/packages/flutter/test/widgets/scrollable_semantics_traversal_order_test.dart index 96a41661f15..cee63a605ef 100644 --- a/packages/flutter/test/widgets/scrollable_semantics_traversal_order_test.dart +++ b/packages/flutter/test/widgets/scrollable_semantics_traversal_order_test.dart @@ -71,6 +71,7 @@ void main() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], children: [ TestSemantics( @@ -245,6 +246,7 @@ void main() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], children: [ TestSemantics( @@ -376,6 +378,7 @@ void main() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], children: [ TestSemantics( @@ -515,6 +518,7 @@ void main() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], children: [ TestSemantics( @@ -671,6 +675,7 @@ void main() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], children: children, ), @@ -744,6 +749,7 @@ void main() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], children: [ TestSemantics( diff --git a/packages/flutter/test/widgets/scrollbar_test.dart b/packages/flutter/test/widgets/scrollbar_test.dart index 01695da7773..3895ff995ff 100644 --- a/packages/flutter/test/widgets/scrollbar_test.dart +++ b/packages/flutter/test/widgets/scrollbar_test.dart @@ -3267,7 +3267,7 @@ The provided ScrollController cannot be shared by multiple ScrollView widgets.'' // that begin in the center of the scrollable are handled by the // scrollable, not the scrollbar. However: the scrollbar widget does // contain the scrollable and this test verifies that it doesn't - // inadvertantly handle thumb down/start/update/end gestures due + // inadvertently handle thumb down/start/update/end gestures due // to trackpad pan/zoom events. Those callbacks are prevented by // the overrides of isPointerPanZoomAllowed in the scrollbar // gesture recognizers. diff --git a/packages/flutter/test/widgets/selectable_region_context_menu_test.dart b/packages/flutter/test/widgets/selectable_region_context_menu_test.dart index 0c87f13ea7e..a68cd1b675d 100644 --- a/packages/flutter/test/widgets/selectable_region_context_menu_test.dart +++ b/packages/flutter/test/widgets/selectable_region_context_menu_test.dart @@ -161,6 +161,14 @@ class RenderSelectionSpy extends RenderProxyBox return const SelectedContent(plainText: 'content'); } + @override + SelectedContentRange? getSelection() { + return null; + } + + @override + int get contentLength => 1; + @override final SelectionGeometry value = const SelectionGeometry( hasContent: true, diff --git a/packages/flutter/test/widgets/selectable_region_test.dart b/packages/flutter/test/widgets/selectable_region_test.dart index bb8a0ac483a..4028215c6e9 100644 --- a/packages/flutter/test/widgets/selectable_region_test.dart +++ b/packages/flutter/test/widgets/selectable_region_test.dart @@ -40,13 +40,9 @@ void main() { group('SelectableRegion', () { testWidgets('mouse selection single click sends correct events', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), @@ -81,13 +77,10 @@ void main() { testWidgets('mouse double click sends select-word event', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), @@ -112,13 +105,10 @@ void main() { testWidgets('touch double click sends select-word event', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), @@ -143,9 +133,6 @@ void main() { testWidgets('Does not crash when using Navigator pages', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/119776 - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: Navigator( @@ -155,7 +142,6 @@ void main() { children: [ const Text('How are you?'), SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const SelectAllWidget(child: SizedBox(width: 100, height: 100)), ), @@ -177,8 +163,6 @@ void main() { testWidgets('can draw handles when they are at rect boundaries', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( @@ -186,7 +170,6 @@ void main() { children: [ const Text('How are you?'), SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectAllWidget(key: spy, child: const SizedBox(width: 100, height: 100)), ), @@ -210,13 +193,10 @@ void main() { testWidgets('touch does not accept drag', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), @@ -236,13 +216,10 @@ void main() { testWidgets('does not merge semantics node of the children', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Scaffold( body: Center( @@ -315,8 +292,6 @@ void main() { testWidgets('Horizontal PageView beats SelectionArea child touch drag gestures on iOS', (WidgetTester tester) async { final PageController pageController = PageController(); const String testValue = 'abc def ghi jkl mno pqr stu vwx yz'; - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); addTearDown(pageController.dispose); await tester.pumpWidget( @@ -326,7 +301,6 @@ void main() { children: [ Center( child: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text(testValue), ), @@ -346,7 +320,7 @@ void main() { final Offset gPos = textOffsetToPosition(paragraph, testValue.indexOf('g')); final Offset pPos = textOffsetToPosition(paragraph, testValue.indexOf('p')); - // A double tap + drag should take precendence over parent drags. + // A double tap + drag should take precedence over parent drags. final TestGesture gesture = await tester.startGesture(gPos); addTearDown(gesture.removePointer); await tester.pump(); @@ -379,8 +353,6 @@ void main() { // Regression test for https://github.com/flutter/flutter/issues/150897. final PageController pageController = PageController(); const String testValue = 'abc def ghi jkl mno pqr stu vwx yz'; - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); addTearDown(pageController.dispose); await tester.pumpWidget( @@ -391,7 +363,6 @@ void main() { children: [ Center( child: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text(testValue), ), @@ -411,7 +382,7 @@ void main() { final Offset gPos = textOffsetToPosition(paragraph, testValue.indexOf('g')); final Offset pPos = textOffsetToPosition(paragraph, testValue.indexOf('p')); - // A double tap + drag should take precendence over parent drags. + // A double tap + drag should take precedence over parent drags. final TestGesture gesture = await tester.startGesture(gPos); addTearDown(gesture.removePointer); await tester.pump(); @@ -452,13 +423,10 @@ void main() { testWidgets('mouse single-click selection collapses the selection', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), @@ -481,13 +449,10 @@ void main() { testWidgets('touch long press sends select-word event', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), @@ -509,13 +474,10 @@ void main() { testWidgets('touch long press and drag sends correct events', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), @@ -547,13 +509,10 @@ void main() { 'touch long press cancel does not send ClearSelectionEvent', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), @@ -583,8 +542,6 @@ void main() { (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/128765 final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( @@ -594,7 +551,6 @@ void main() { child: SizedBox( height: 2000, child: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), @@ -627,13 +583,10 @@ void main() { testWidgets('mouse long press does not send select-word event', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), @@ -656,19 +609,16 @@ void main() { testWidgets('Can extend StaticSelectionContainerDelegate', (WidgetTester tester) async { SelectedContent? content; - final FocusNode focusNode = FocusNode(); // Inserts a new line between selected content of children selectables. final ColumnSelectionContainerDelegate selectionDelegate = ColumnSelectionContainerDelegate(); - addTearDown(focusNode.dispose); addTearDown(selectionDelegate.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( onSelectionChanged: (SelectedContent? selectedContent) => content = selectedContent, - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionContainer( delegate: selectionDelegate, @@ -711,13 +661,10 @@ void main() { addTearDown(() { tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall); }); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text('How are you?'), ), @@ -814,13 +761,9 @@ void main() { }, variant: TargetPlatformVariant.desktop()); testWidgets('touch can select word-by-word on double tap drag on mobile platforms', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Center( child: Text('How are you'), @@ -890,13 +833,9 @@ void main() { ); testWidgets('touch can select multiple widgets on double tap drag on mobile platforms', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -942,13 +881,9 @@ void main() { ); testWidgets('touch can select multiple widgets on double tap drag and return to origin word on mobile platforms', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -1006,13 +941,9 @@ void main() { ); testWidgets('touch can reverse selection across multiple widgets on double tap drag on mobile platforms', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -1063,13 +994,9 @@ void main() { 'This will be the start of a new line. When triple clicking this block ' 'of text all of it should be selected.'; - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Center( child: Text(longText), @@ -1166,13 +1093,9 @@ void main() { ); testWidgets('touch cannot select word-by-word on double tap drag when on Android web', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Center( child: Text('How are you'), @@ -1219,13 +1142,9 @@ void main() { ); testWidgets('touch can double tap + drag on iOS web', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Center( child: Text('How are you'), @@ -1275,13 +1194,9 @@ void main() { ); testWidgets('touch cannot double tap on iOS web', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Center( child: Text('How are you'), @@ -1311,15 +1226,12 @@ void main() { testWidgets('RenderParagraph should invalidate cachedRect on window size change', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/155143. - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); addTearDown(tester.view.reset); const String testString = 'How are you doing today? Good, and you?'; await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Center( child: Text(testString), @@ -1366,14 +1278,11 @@ void main() { testWidgets('RenderParagraph should invalidate cached bounding boxes', (WidgetTester tester) async { final UniqueKey outerText = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); addTearDown(tester.view.reset); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Scaffold( body: Center( @@ -1427,13 +1336,9 @@ void main() { }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. testWidgets('mouse can select single text on desktop platforms', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Center( child: Text('How are you'), @@ -1478,13 +1383,9 @@ void main() { }, variant: TargetPlatformVariant.desktop()); testWidgets('mouse can select single text on mobile platforms', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Center( child: Text('How are you'), @@ -1530,14 +1431,91 @@ void main() { await gesture.up(); }, variant: TargetPlatformVariant.mobile()); - testWidgets('mouse can select word-by-word on double click drag', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - + testWidgets('mouse drag finalizes the selection', (WidgetTester tester) async { + SelectableRegionSelectionStatus? selectionStatus; + final GlobalKey textKey = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: Center( + child: Text( + key: textKey, + 'How are you', + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(textKey.currentContext, isNotNull); + final ValueListenable? selectionStatusNotifier = SelectableRegionSelectionStatusScope.maybeOf(textKey.currentContext!); + void onSelectionStatusChange() { + selectionStatus = selectionStatusNotifier?.value; + } + selectionStatusNotifier?.addListener(onSelectionStatusChange); + addTearDown(() { + selectionStatusNotifier?.removeListener(onSelectionStatusChange); + }); + final RenderParagraph paragraph = tester.renderObject(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); + final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse); + addTearDown(gesture.removePointer); + await tester.pump(); + + await gesture.moveTo(textOffsetToPosition(paragraph, 4)); + await tester.pump(); + expect(selectionStatus, SelectableRegionSelectionStatus.changing); + await gesture.up(); + await tester.pump(); + + expect(paragraph.selections.length, 1); + expect(selectionStatus, SelectableRegionSelectionStatus.finalized); + }, variant: TargetPlatformVariant.all()); + + testWidgets('touch drag does not finalize selection on mobile platforms', (WidgetTester tester) async { + SelectableRegionSelectionStatus? selectionStatus; + final GlobalKey textKey = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: Center( + child: Text( + key: textKey, + 'How are you', + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(textKey.currentContext, isNotNull); + final ValueListenable? selectionStatusNotifier = SelectableRegionSelectionStatusScope.maybeOf(textKey.currentContext!); + void onSelectionStatusChange() { + selectionStatus = selectionStatusNotifier?.value; + } + selectionStatusNotifier?.addListener(onSelectionStatusChange); + addTearDown(() { + selectionStatusNotifier?.removeListener(onSelectionStatusChange); + }); + final RenderParagraph paragraph = tester.renderObject(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); + final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2)); + addTearDown(gesture.removePointer); + await tester.pump(); + + await gesture.moveTo(textOffsetToPosition(paragraph, 4)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + expect(paragraph.selections.length, 0); + expect(selectionStatus, isNull); + }, variant: TargetPlatformVariant.mobile()); + + testWidgets('mouse can select word-by-word on double click drag', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Center( child: Text('How are you'), @@ -1604,13 +1582,9 @@ void main() { }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. testWidgets('mouse can select multiple widgets on double click drag', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -1653,13 +1627,9 @@ void main() { }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. testWidgets('mouse can select multiple widgets on double click drag and return to origin word', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -1714,13 +1684,9 @@ void main() { }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. testWidgets('mouse can reverse selection across multiple widgets on double click drag', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -1768,13 +1734,9 @@ void main() { 'This will be the start of a new line. When triple clicking this block ' 'of text all of it should be selected.'; - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Center( child: Text(longText), @@ -1843,13 +1805,9 @@ void main() { }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. testWidgets('mouse can select multiple widgets on triple click drag when selecting inside a WidgetSpan', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text.rich( WidgetSpan( @@ -1899,13 +1857,9 @@ void main() { }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. testWidgets('mouse can select multiple widgets on triple click drag', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -1965,13 +1919,9 @@ void main() { }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. testWidgets('mouse can select multiple widgets on triple click drag and return to origin paragraph', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -2041,13 +1991,9 @@ void main() { }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. testWidgets('mouse can reverse selection across multiple widgets on triple click drag', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -2094,13 +2040,9 @@ void main() { }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. testWidgets('mouse can select multiple widgets', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -2137,13 +2079,9 @@ void main() { }); testWidgets('mouse shift + click holds the selection start in place and moves the end', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -2200,13 +2138,9 @@ void main() { }, variant: TargetPlatformVariant.desktop()); testWidgets('mouse shift + click collapses the selection when it has not been initialized', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -2234,13 +2168,9 @@ void main() { }, variant: TargetPlatformVariant.desktop()); testWidgets('collapsing selection should clear selection of all other selectables', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -2280,13 +2210,9 @@ void main() { }); testWidgets('mouse can work with disabled container', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -2324,13 +2250,9 @@ void main() { }); testWidgets('mouse can reverse selection', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -2374,12 +2296,9 @@ void main() { final bool isPlatformAndroid = defaultTargetPlatform == TargetPlatform.android; Set buttonTypes = {}; final UniqueKey toolbarKey = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, @@ -2466,13 +2385,10 @@ void main() { (WidgetTester tester) async { Set buttonTypes = {}; final UniqueKey toolbarKey = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, @@ -2542,13 +2458,10 @@ void main() { (WidgetTester tester) async { Set buttonTypes = {}; final UniqueKey toolbarKey = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, @@ -2626,13 +2539,10 @@ void main() { // Regression test for https://github.com/flutter/flutter/issues/150268. Set buttonTypes = {}; final UniqueKey toolbarKey = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, @@ -2701,13 +2611,10 @@ void main() { (WidgetTester tester) async { Set buttonTypes = {}; final UniqueKey toolbarKey = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, @@ -2808,13 +2715,10 @@ void main() { (WidgetTester tester) async { Set buttonTypes = {}; final UniqueKey toolbarKey = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, @@ -2931,13 +2835,10 @@ void main() { (WidgetTester tester) async { Set buttonTypes = {}; final UniqueKey toolbarKey = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, @@ -3058,13 +2959,10 @@ void main() { ); testWidgets('can copy a selection made with the mouse', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -3243,13 +3141,10 @@ void main() { testWidgets( 'mouse selection can handle widget span', (WidgetTester tester) async { final UniqueKey outerText = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Center( child: Text.rich( @@ -3285,13 +3180,10 @@ void main() { testWidgets( 'double click + drag mouse selection can handle widget span', (WidgetTester tester) async { final UniqueKey outerText = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Center( child: Text.rich( @@ -3333,13 +3225,10 @@ void main() { 'double click + drag mouse selection can handle widget span - multiline', (WidgetTester tester) async { final UniqueKey outerText = UniqueKey(); final UniqueKey innerText = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Center( child: Text.rich( @@ -3384,13 +3273,10 @@ void main() { 'select word event can select inline widget', (WidgetTester tester) async { final UniqueKey outerText = UniqueKey(); final UniqueKey innerText = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Center( child: Text.rich( @@ -3437,7 +3323,6 @@ void main() { await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Scaffold( body: Center( @@ -3478,13 +3363,10 @@ void main() { 'can select word when a selectables rect is completely inside of another selectables rect', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/127076. final UniqueKey outerText = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Scaffold( body: Center( @@ -3524,13 +3406,10 @@ void main() { testWidgets( 'can select word when selectable is broken up by an unselectable WidgetSpan', (WidgetTester tester) async { final UniqueKey outerText = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Scaffold( body: Center( @@ -3571,13 +3450,10 @@ void main() { 'widget span is ignored if it does not contain text - non Apple', (WidgetTester tester) async { final UniqueKey outerText = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Center( child: Text.rich( @@ -3614,13 +3490,10 @@ void main() { 'widget span is ignored if it does not contain text - Apple', (WidgetTester tester) async { final UniqueKey outerText = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Center( child: Text.rich( @@ -3654,13 +3527,10 @@ void main() { ); testWidgets('mouse can select across bidi text', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -3698,13 +3568,10 @@ void main() { }, skip: isBrowser); // https://github.com/flutter/flutter/issues/61020 testWidgets('long press and drag touch moves selection word by word', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -3733,8 +3600,6 @@ void main() { testWidgets('can drag end handle when not covering entire screen', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/104620. - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( @@ -3742,7 +3607,6 @@ void main() { children: [ const Text('How are you?'), SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text('Good, and you?'), ), @@ -3773,8 +3637,6 @@ void main() { testWidgets('can drag start handle when not covering entire screen', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/104620. - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( @@ -3782,7 +3644,6 @@ void main() { children: [ const Text('How are you?'), SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text('Good, and you?'), ), @@ -3811,13 +3672,10 @@ void main() { }); testWidgets('can drag start selection handle', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -3856,13 +3714,10 @@ void main() { }); testWidgets('can drag start selection handle across end selection handle', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -3896,13 +3751,10 @@ void main() { }); testWidgets('can drag end selection handle across start selection handle', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -3936,13 +3788,10 @@ void main() { }); testWidgets('can select all from toolbar', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -3975,13 +3824,10 @@ void main() { }, skip: kIsWeb); // [intended] Web uses its native context menu. testWidgets('can copy from toolbar', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -4018,13 +3864,10 @@ void main() { }, skip: kIsWeb); // [intended] Web uses its native context menu. testWidgets('can use keyboard to granularly extend selection - character', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -4081,13 +3924,10 @@ void main() { }, variant: TargetPlatformVariant.all()); testWidgets('can use keyboard to granularly extend selection - word', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -4196,13 +4036,10 @@ void main() { }, variant: TargetPlatformVariant.all()); testWidgets('can use keyboard to granularly extend selection - line', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -4290,13 +4127,10 @@ void main() { }, variant: TargetPlatformVariant.all()); testWidgets('can use keyboard to granularly extend selection - document', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -4373,13 +4207,10 @@ void main() { }, variant: TargetPlatformVariant.all()); testWidgets('can use keyboard to directionally extend selection', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -4477,8 +4308,6 @@ void main() { testWidgets('Can drag handles to show, unshow, and update magnifier', (WidgetTester tester) async { const String text = 'Monkeys and rabbits in my soup'; - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( @@ -4492,7 +4321,6 @@ void main() { return fakeMagnifier; }, ), - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text(text), ), @@ -4544,13 +4372,10 @@ void main() { testWidgets('toolbar is hidden on Android and iOS when orientation changes', (WidgetTester tester) async { addTearDown(tester.view.reset); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text('How are you?'), ), @@ -4612,13 +4437,10 @@ void main() { testWidgets('the selection behavior when clicking `Copy` item in mobile platforms', (WidgetTester tester) async { List buttonItems = []; - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, @@ -4668,13 +4490,10 @@ void main() { testWidgets('the handles do not disappear when clicking `Select all` item in mobile platforms', (WidgetTester tester) async { List buttonItems = []; - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, @@ -4735,13 +4554,10 @@ void main() { testWidgets('Selection behavior when clicking the `Share` button on Android', (WidgetTester tester) async { List buttonItems = []; - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, @@ -4795,13 +4611,10 @@ void main() { testWidgets('builds the correct button items', (WidgetTester tester) async { List buttonItems = []; - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, @@ -4855,13 +4668,10 @@ void main() { ); testWidgets('can clear selection through SelectableRegionState', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -4905,7 +4715,7 @@ void main() { await gesture.up(); await tester.pumpAndSettle(); - // Clear selection programatically. + // Clear selection programmatically. state.clearSelection(); expect(paragraph1.selections, isEmpty); expect(paragraph2.selections, isEmpty); @@ -4919,13 +4729,10 @@ void main() { addTearDown(() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.processText, null)); Set buttonLabels = {}; - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, @@ -4966,16 +4773,258 @@ void main() { skip: kIsWeb, // [intended] Web uses its native context menu. ); + testWidgets('SelectionListener onSelectionChanged is accurate with WidgetSpans', (WidgetTester tester) async { + final List dataModel = [ + 'Hello world, ', + 'how are you today.', + ]; + final SelectionListenerNotifier selectionNotifier = SelectionListenerNotifier(); + addTearDown(selectionNotifier.dispose); + + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: SelectionListener( + selectionNotifier: selectionNotifier, + child: Column( + children: [ + Text.rich( + TextSpan( + text: dataModel[0], + children: [ + WidgetSpan( + child: Text( + dataModel[1], + ), + ), + ], + ), + ), + ], + ), + ), + ), + ), + ); + + final RenderParagraph paragraph1 = tester.renderObject(find.descendant(of: find.textContaining('Hello world'), matching: find.byType(RichText).first)); + final RenderParagraph paragraph2 = tester.renderObject(find.descendant(of: find.text('how are you today.'), matching: find.byType(RichText))); + final TestGesture mouseGesture = await tester.startGesture(textOffsetToPosition(paragraph1, 0), kind: PointerDeviceKind.mouse); + + addTearDown(mouseGesture.removePointer); + await tester.pump(); + + SelectedContentRange? selectedRange; + + // Selection on paragraph1. + await mouseGesture.moveTo(textOffsetToPosition(paragraph1, 1)); + await tester.pumpAndSettle(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 0); + expect(selectedRange.endOffset, 1); + + // Selection on paragraph1. + await mouseGesture.moveTo(textOffsetToPosition(paragraph1, 10)); + await tester.pumpAndSettle(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 0); + expect(selectedRange.endOffset, 10); + + // Selection on paragraph1 and paragraph2. + await mouseGesture.moveTo(textOffsetToPosition(paragraph2, 10)); + await tester.pumpAndSettle(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 0); + expect(selectedRange.endOffset, 23); + await mouseGesture.up(); + await tester.pump(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 0); + expect(selectedRange.endOffset, 23); + + // Collapsed selection. + await mouseGesture.down(textOffsetToPosition(paragraph2, 3)); + await tester.pump(); + await mouseGesture.up(); + await tester.pumpAndSettle(kDoubleTapTimeout); + expect(selectionNotifier.selection.status, SelectionStatus.collapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 16); + expect(selectedRange.endOffset, 16); + + // Backwards selection. + await mouseGesture.down(textOffsetToPosition(paragraph2, 4)); + await tester.pump(); + await mouseGesture.moveTo(textOffsetToPosition(paragraph1, 0)); + await tester.pumpAndSettle(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 17); + expect(selectedRange.endOffset, 0); + await mouseGesture.up(); + await tester.pump(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 17); + expect(selectedRange.endOffset, 0); + + // Collapsed selection. + await mouseGesture.down(textOffsetToPosition(paragraph1, 0)); + await tester.pumpAndSettle(); + await mouseGesture.up(); + await tester.pumpAndSettle(kDoubleTapTimeout); + expect(selectionNotifier.selection.status, SelectionStatus.collapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 0); + expect(selectedRange.endOffset, 0); + }); + + testWidgets('onSelectionChanged SelectedContentRange is accurate', (WidgetTester tester) async { + final List dataModel = [ + 'How are you?', + 'Good, and you?', + 'Fine, thank you.', + ]; + final SelectionListenerNotifier selectionNotifier = SelectionListenerNotifier(); + SelectedContentRange? selectedRange; + addTearDown(selectionNotifier.dispose); + + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: SelectionListener( + selectionNotifier: selectionNotifier, + child: Column( + children: [ + Text( + dataModel[0], + ), + Text( + dataModel[1], + ), + Text( + dataModel[2], + ), + ], + ), + ), + ), + ), + ); + + final RenderParagraph paragraph1 = tester.renderObject(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph2 = tester.renderObject(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph3 = tester.renderObject(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); + final TestGesture mouseGesture = await tester.startGesture(textOffsetToPosition(paragraph1, 4), kind: PointerDeviceKind.mouse); + + addTearDown(mouseGesture.removePointer); + await tester.pump(); + + // Selection on paragraph1. + await mouseGesture.moveTo(textOffsetToPosition(paragraph1, 7)); + await tester.pumpAndSettle(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 4); + expect(selectedRange.endOffset, 7); + + // Selection on paragraph1. + await mouseGesture.moveTo(textOffsetToPosition(paragraph1, 10)); + await tester.pumpAndSettle(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 4); + expect(selectedRange.endOffset, 10); + + // Selection on paragraph1 and paragraph2. + await mouseGesture.moveTo(textOffsetToPosition(paragraph2, 10)); + await tester.pumpAndSettle(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 4); + expect(selectedRange.endOffset, 22); + + // Selection on paragraph1, paragraph2, and paragraph3. + await mouseGesture.moveTo(textOffsetToPosition(paragraph3, 10)); + await tester.pumpAndSettle(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 4); + expect(selectedRange.endOffset, 36); + await mouseGesture.up(); + await tester.pump(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 4); + expect(selectedRange.endOffset, 36); + + // Collapsed selection. + await mouseGesture.down(textOffsetToPosition(paragraph1, 3)); + await tester.pump(); + await mouseGesture.up(); + await tester.pumpAndSettle(kDoubleTapTimeout); + expect(selectionNotifier.selection.status, SelectionStatus.collapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 3); + expect(selectedRange.endOffset, 3); + + // Backwards selection. + await mouseGesture.down(textOffsetToPosition(paragraph3, 4)); + await tester.pump(); + await mouseGesture.moveTo(textOffsetToPosition(paragraph1, 0)); + await tester.pumpAndSettle(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 30); + expect(selectedRange.endOffset, 0); + await mouseGesture.up(); + await tester.pump(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 30); + expect(selectedRange.endOffset, 0); + + // Collapsed selection. + await mouseGesture.down(textOffsetToPosition(paragraph1, 0)); + await tester.pumpAndSettle(); + await mouseGesture.up(); + await tester.pumpAndSettle(kDoubleTapTimeout); + expect(selectionNotifier.selection.status, SelectionStatus.collapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 0); + expect(selectedRange.endOffset, 0); + }); + testWidgets('onSelectionChange is called when the selection changes through gestures', (WidgetTester tester) async { SelectedContent? content; - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( onSelectionChanged: (SelectedContent? selectedContent) => content = selectedContent, - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Center( child: Text('How are you'), @@ -5109,14 +5158,11 @@ void main() { testWidgets('onSelectionChange is called when the selection changes through keyboard actions', (WidgetTester tester) async { SelectedContent? content; - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( onSelectionChanged: (SelectedContent? selectedContent) => content = selectedContent, - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: [ @@ -5268,14 +5314,11 @@ void main() { }); testWidgets('web can show flutter context menu when the browser context menu is disabled', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( onSelectionChanged: (SelectedContent? selectedContent) {}, - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Center( child: Text('How are you'), @@ -5305,13 +5348,10 @@ void main() { // Regression test for https://github.com/flutter/flutter/issues/127942. final UniqueKey outerText = UniqueKey(); const TextStyle textStyle = TextStyle(fontSize: 10); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Scaffold( body: Center( @@ -5425,6 +5465,14 @@ class RenderSelectionSpy extends RenderProxyBox return const SelectedContent(plainText: 'content'); } + @override + SelectedContentRange? getSelection() { + return null; + } + + @override + int get contentLength => 1; + @override final SelectionGeometry value = const SelectionGeometry( hasContent: true, @@ -5507,6 +5555,14 @@ class RenderSelectAll extends RenderProxyBox return const SelectedContent(plainText: 'content'); } + @override + SelectedContentRange? getSelection() { + return null; + } + + @override + int get contentLength => 1; + @override SelectionGeometry get value => _value; SelectionGeometry _value = const SelectionGeometry( diff --git a/packages/flutter/test/widgets/selectable_text_test.dart b/packages/flutter/test/widgets/selectable_text_test.dart index f9bf5c08f16..a345b774e9f 100644 --- a/packages/flutter/test/widgets/selectable_text_test.dart +++ b/packages/flutter/test/widgets/selectable_text_test.dart @@ -1391,6 +1391,36 @@ void main() { expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(newFourthPos)), isFalse); }); + testWidgets('ScrollBehavior can be overridden', (WidgetTester tester) async { + await tester.pumpWidget( + boilerplate( + child: const SelectableText( + kMoreThanFourLines, + dragStartBehavior: DragStartBehavior.down, + style: TextStyle(color: Colors.black, fontSize: 34.0), + maxLines: 2, + ), + ), + ); + expect(tester.widget(find.byType(EditableText)).scrollBehavior, isNull); + expect(tester.widget(find.byType(Scrollable)).scrollBehavior, isNotNull); + + final ScrollBehavior behavior = const ScrollBehavior()..copyWith(scrollbars: false); + await tester.pumpWidget( + boilerplate( + child: SelectableText( + kMoreThanFourLines, + dragStartBehavior: DragStartBehavior.down, + style: const TextStyle(color: Colors.black, fontSize: 34.0), + maxLines: 2, + scrollBehavior: behavior, + ), + ), + ); + expect(tester.widget(find.byType(EditableText)).scrollBehavior, equals(behavior)); + expect(tester.widget(find.byType(Scrollable)).scrollBehavior, equals(behavior)); + }); + testWidgets('minLines cannot be greater than maxLines', (WidgetTester tester) async { expect( () async { @@ -2595,7 +2625,7 @@ void main() { children: [ TestSemantics( flags: [SemanticsFlag.hasImplicitScrolling], - actions: [SemanticsAction.scrollUp], + actions: [SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], children: [ TestSemantics( actions: [SemanticsAction.longPress], @@ -3563,7 +3593,7 @@ void main() { final Offset gPos = textOffsetToPosition(tester, testValue.indexOf('g')); final Offset pPos = textOffsetToPosition(tester, testValue.indexOf('p')); - // A double tap + drag should take precendence over parent drags. + // A double tap + drag should take precedence over parent drags. final TestGesture gesture = await tester.startGesture(gPos); await tester.pump(); await gesture.up(); @@ -4578,6 +4608,7 @@ void main() { cursorRadius: Radius.zero, cursorColor: Color(0xff00ff00), scrollPhysics: ClampingScrollPhysics(), + scrollBehavior: ScrollBehavior(), semanticsLabel: 'something else', enableInteractiveSelection: false, ).debugFillProperties(builder); @@ -4603,6 +4634,7 @@ void main() { 'cursorColor: ${const Color(0xff00ff00)}', 'selection disabled', 'scrollPhysics: ClampingScrollPhysics', + 'scrollBehavior: ScrollBehavior', ]); }); diff --git a/packages/flutter/test/widgets/semantics_debugger_test.dart b/packages/flutter/test/widgets/semantics_debugger_test.dart index 47b8243300e..7edcffd50d9 100644 --- a/packages/flutter/test/widgets/semantics_debugger_test.dart +++ b/packages/flutter/test/widgets/semantics_debugger_test.dart @@ -61,6 +61,26 @@ void main() { expect(true, isTrue); // expect that we reach here without crashing }); + testWidgets('SemanticsDebugger draw persistent color based on structure', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: SemanticsDebugger( + child: Stack( + children: [ + Semantics( + container: true, + child: Semantics(container: true), + ), + ], + ), + ), + ), + ); + + expect(find.byType(SemanticsDebugger), paints..rect()..rect(color: const Color(0xFFF866FF))); + }); + testWidgets('SemanticsDebugger reparents subtree', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); diff --git a/packages/flutter/test/widgets/semantics_test.dart b/packages/flutter/test/widgets/semantics_test.dart index 66dcd7ddb0f..ea552844cc0 100644 --- a/packages/flutter/test/widgets/semantics_test.dart +++ b/packages/flutter/test/widgets/semantics_test.dart @@ -524,7 +524,8 @@ void main() { ..remove(SemanticsAction.moveCursorForwardByWord) ..remove(SemanticsAction.moveCursorBackwardByWord) ..remove(SemanticsAction.customAction) // customAction is not user-exposed. - ..remove(SemanticsAction.showOnScreen); // showOnScreen is not user-exposed + ..remove(SemanticsAction.showOnScreen) // showOnScreen is not user-exposed + ..remove(SemanticsAction.scrollToOffset); // scrollToOffset is not user-exposed const int expectedId = 1; final TestSemantics expectedSemantics = TestSemantics.root( @@ -569,6 +570,7 @@ void main() { case SemanticsAction.scrollLeft: case SemanticsAction.scrollRight: case SemanticsAction.scrollUp: + case SemanticsAction.scrollToOffset: case SemanticsAction.showOnScreen: case SemanticsAction.tap: case SemanticsAction.focus: diff --git a/packages/flutter/test/widgets/single_child_scroll_view_test.dart b/packages/flutter/test/widgets/single_child_scroll_view_test.dart index d84f52fd6ea..6f6aac84103 100644 --- a/packages/flutter/test/widgets/single_child_scroll_view_test.dart +++ b/packages/flutter/test/widgets/single_child_scroll_view_test.dart @@ -354,6 +354,7 @@ void main() { ], actions: [ SemanticsAction.scrollUp, + SemanticsAction.scrollToOffset, ], children: generateSemanticsChildren(endHidden: 3), ), @@ -375,6 +376,7 @@ void main() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], children: generateSemanticsChildren(startHidden: 14, endHidden: 18), ), @@ -395,6 +397,7 @@ void main() { ], actions: [ SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], children: generateSemanticsChildren(startHidden: 26), ), diff --git a/packages/flutter/test/widgets/sliver_main_axis_group_test.dart b/packages/flutter/test/widgets/sliver_main_axis_group_test.dart index 7c9239972be..7e84f0237ae 100644 --- a/packages/flutter/test/widgets/sliver_main_axis_group_test.dart +++ b/packages/flutter/test/widgets/sliver_main_axis_group_test.dart @@ -198,7 +198,7 @@ void main() { const Rect.fromLTRB(0.0, 0.0, 200.0, 600.0), ); - final List renderSlivers = tester.renderObjectList(find.byType(SliverList)).toList(); + final List renderSlivers = tester.renderObjectList(find.byType(SliverList, skipOffstage: false)).toList(); final RenderSliverList first = renderSlivers[0]; final RenderSliverList second = renderSlivers[1]; @@ -268,7 +268,7 @@ void main() { const Rect.fromLTRB(100.0, 0.0, 300.0, 600.0), ); - final List renderSlivers = tester.renderObjectList(find.byType(SliverList)).toList(); + final List renderSlivers = tester.renderObjectList(find.byType(SliverList, skipOffstage: false)).toList(); final RenderSliverList first = renderSlivers[0]; final RenderSliverList second = renderSlivers[1]; @@ -598,7 +598,7 @@ void main() { await tester.pumpAndSettle(); // At a scroll offset of 630, a normal scrolling header should be out of view. - final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; + final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader, skipOffstage: false)) as RenderSliverPersistentHeader; expect(renderHeader.constraints.scrollOffset, equals(630)); expect(renderHeader.geometry!.layoutExtent, equals(0.0)); }); @@ -855,6 +855,20 @@ void main() { expect(tester.getTopLeft(find.byKey(firstTextFieldKey)), const Offset(0, 60)); }); + + testWidgets('SliverMainAxisGroup offstage child', (WidgetTester tester) async { + await tester.pumpWidget( + _buildSliverMainAxisGroup( + viewportHeight: 300, + slivers: [ + const SliverToBoxAdapter(child: SizedBox(height: 300)), + const SliverToBoxAdapter(child: SizedBox(height: 100, child: Text('1'))), + ] + ) + ); + expect(find.text('1'), findsNothing); + expect(find.text('1', skipOffstage: false), findsOneWidget); + }); } Widget _buildSliverList({ diff --git a/packages/flutter/test/widgets/sliver_semantics_test.dart b/packages/flutter/test/widgets/sliver_semantics_test.dart index c7d5981a8e1..596128f6565 100644 --- a/packages/flutter/test/widgets/sliver_semantics_test.dart +++ b/packages/flutter/test/widgets/sliver_semantics_test.dart @@ -94,7 +94,7 @@ void _tests() { flags: [ SemanticsFlag.hasImplicitScrolling, ], - actions: [SemanticsAction.scrollUp], + actions: [SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], children: [ TestSemantics( id: 3, @@ -165,6 +165,7 @@ void _tests() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], flags: [SemanticsFlag.hasImplicitScrolling], children: [ @@ -244,6 +245,7 @@ void _tests() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], children: [ TestSemantics( @@ -339,6 +341,7 @@ void _tests() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], children: [ TestSemantics( @@ -521,6 +524,7 @@ void _tests() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], flags: [SemanticsFlag.hasImplicitScrolling], children: [ @@ -633,6 +637,7 @@ void _tests() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], flags: [SemanticsFlag.hasImplicitScrolling], children: [ @@ -736,6 +741,7 @@ void _tests() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], children: [ TestSemantics( @@ -851,6 +857,7 @@ void _tests() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], children: [ TestSemantics( @@ -1007,6 +1014,7 @@ void _tests() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], flags: [SemanticsFlag.hasImplicitScrolling], children: [ @@ -1069,6 +1077,7 @@ void _tests() { actions: [ SemanticsAction.scrollUp, SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, ], children: [ TestSemantics( diff --git a/packages/flutter/test/widgets/slivers_appbar_floating_pinned_test.dart b/packages/flutter/test/widgets/slivers_appbar_floating_pinned_test.dart index cab6bf787a5..1118d519621 100644 --- a/packages/flutter/test/widgets/slivers_appbar_floating_pinned_test.dart +++ b/packages/flutter/test/widgets/slivers_appbar_floating_pinned_test.dart @@ -106,7 +106,7 @@ void main() { ], ), TestSemantics( - actions: [SemanticsAction.scrollUp], + actions: [SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], flags: [SemanticsFlag.hasImplicitScrolling], scrollIndex: 0, children: [ @@ -171,7 +171,7 @@ void main() { ], ), TestSemantics( - actions: [SemanticsAction.scrollUp, SemanticsAction.scrollDown], + actions: [SemanticsAction.scrollUp, SemanticsAction.scrollDown, SemanticsAction.scrollToOffset], flags: [SemanticsFlag.hasImplicitScrolling], scrollIndex: 11, children: [ diff --git a/packages/flutter/test/widgets/text_test.dart b/packages/flutter/test/widgets/text_test.dart index e38fa88c041..13a5762a71e 100644 --- a/packages/flutter/test/widgets/text_test.dart +++ b/packages/flutter/test/widgets/text_test.dart @@ -674,7 +674,7 @@ void main() { children: [ TestSemantics( flags: [SemanticsFlag.hasImplicitScrolling], - actions: [SemanticsAction.scrollUp], + actions: [SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], children: [ TestSemantics( children: [ diff --git a/packages/flutter/test/widgets/widget_inspector_test.dart b/packages/flutter/test/widgets/widget_inspector_test.dart index e4e9c2fb5c7..150aa895ca6 100644 --- a/packages/flutter/test/widgets/widget_inspector_test.dart +++ b/packages/flutter/test/widgets/widget_inspector_test.dart @@ -285,9 +285,6 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { static void runTests() { final TestWidgetInspectorService service = TestWidgetInspectorService(); WidgetInspectorService.instance = service; - setUp(() { - WidgetInspectorService.instance.isSelectMode.value = true; - }); tearDown(() async { service.resetAllState(); @@ -357,7 +354,8 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { const Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( - selectButtonBuilder: null, + exitWidgetSelectionButtonBuilder: null, + moveExitWidgetSelectionButtonBuilder: null, child: Stack( children: [ Text('a', textDirection: TextDirection.ltr), @@ -373,13 +371,23 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { }); testWidgets('WidgetInspector interaction test', (WidgetTester tester) async { + // Enable widget selection mode. + WidgetInspectorService.instance.isSelectMode = true; + final List log = []; - final GlobalKey selectButtonKey = GlobalKey(); + late GlobalKey exitWidgetSelectionButtonKey; final GlobalKey inspectorKey = GlobalKey(); final GlobalKey topButtonKey = GlobalKey(); + final GlobalKey bottomButtonKey = GlobalKey(); - Widget selectButtonBuilder(BuildContext context, VoidCallback onPressed) { - return Material(child: ElevatedButton(onPressed: onPressed, key: selectButtonKey, child: null)); + Widget exitWidgetSelectionButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + required GlobalKey key, + }) { + exitWidgetSelectionButtonKey = key; + return Material( + child: ElevatedButton(onPressed: onPressed, key: key, child: null)); } String paragraphText(RenderParagraph paragraph) { @@ -387,12 +395,56 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { return textSpan.text!; } + + Future tapAndVerifyWidgetSelection( + Finder widgetFinder, { + required bool isSelected, + required GlobalKey widgetKey, + }) async { + // Tap on the widget. + await tester.tap(widgetFinder, warnIfMissed: false); + await tester.pump(); + + // Verify the tap was intercepted by the Widget Inspector. + final RenderObject renderObject = + find.byKey(widgetKey).evaluate().first.renderObject!; + expect( + WidgetInspectorService.instance.selection.candidates, + contains(renderObject), + ); + } + + Future panAndVerifyWidgetSelection({ + required Finder startAt, + required Finder endAt, + required bool isSelected, + required GlobalKey widgetKey, + }) async { + // Pan to the widget. + final ui.Offset start = tester.getCenter(startAt); + final ui.Offset end = tester.getCenter(endAt); + await tester.dragFrom( + tester.getCenter(startAt), + Offset(end.dx - start.dx, end.dy - start.dy), + ); + await tester.pump(); + + // Verify the pan end was intercepted by the Widget Inspector. + final RenderObject renderObject = + find.byKey(widgetKey).evaluate().first.renderObject!; + expect( + WidgetInspectorService.instance.selection.candidates, + contains(renderObject), + ); + } + await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( key: inspectorKey, - selectButtonBuilder: selectButtonBuilder, + exitWidgetSelectionButtonBuilder: exitWidgetSelectionButtonBuilder, + moveExitWidgetSelectionButtonBuilder: null, child: Material( child: ListView( children: [ @@ -404,6 +456,7 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { child: const Text('TOP'), ), ElevatedButton( + key: bottomButtonKey, onPressed: () { log.add('bottom'); }, @@ -417,9 +470,13 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { ); expect(WidgetInspectorService.instance.selection.current, isNull); - await tester.tap(find.text('TOP'), warnIfMissed: false); - await tester.pump(); - // Tap intercepted by the inspector + + // Tap on the top button and verify it's selected in the Inspector. + await tapAndVerifyWidgetSelection( + find.text('TOP'), + isSelected: true, + widgetKey: topButtonKey, + ); expect(log, equals([])); expect( paragraphText( @@ -427,35 +484,61 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { ), equals('TOP'), ); - final RenderObject topButton = find.byKey(topButtonKey).evaluate().first.renderObject!; - expect( - WidgetInspectorService.instance.selection.candidates, - contains(topButton), - ); + // Tap on the bottom button and verify it's selected in the Inspector. + await tapAndVerifyWidgetSelection( + find.text('BOTTOM'), + isSelected: true, + widgetKey: bottomButtonKey, + ); + expect( + paragraphText( + WidgetInspectorService.instance.selection.current! as RenderParagraph, + ), + equals('BOTTOM'), + ); + expect(log, equals([])); + + + // Now pan to the top button and verify it's selected in the Inspector. + await panAndVerifyWidgetSelection( + startAt: find.text('BOTTOM'), + endAt: find.text('TOP'), + isSelected: true, + widgetKey: topButtonKey, + ); + expect( + paragraphText( + WidgetInspectorService.instance.selection.current! as RenderParagraph, + ), + equals('TOP'), + ); + expect(log, equals([])); + + // Now pan to the bottom button and verify it's selected in the Inspector. + await panAndVerifyWidgetSelection( + startAt: find.text('TOP'), + endAt: find.text('BOTTOM'), + isSelected: true, + widgetKey: bottomButtonKey, + ); + expect( + paragraphText( + WidgetInspectorService.instance.selection.current! as RenderParagraph, + ), + equals('BOTTOM'), + ); + expect(log, equals([])); + + // Now exit selection mode by tapping the Exit Selection Mode button. + await tester.tap(find.byKey(exitWidgetSelectionButtonKey)); + await tester.pump(); + + // Tap on the top button and verify it is not selected in the Inspector. await tester.tap(find.text('TOP')); expect(log, equals(['top'])); - log.clear(); - await tester.tap(find.text('BOTTOM')); - expect(log, equals(['bottom'])); - log.clear(); - // Ensure the inspector selection has not changed to bottom. - expect( - paragraphText( - WidgetInspectorService.instance.selection.current! as RenderParagraph, - ), - equals('TOP'), - ); - - await tester.tap(find.byKey(selectButtonKey)); - await tester.pump(); - - // We are now back in select mode so tapping the bottom button will have - // not trigger a click but will cause it to be selected. - await tester.tap(find.text('BOTTOM'), warnIfMissed: false); - expect(log, equals([])); - log.clear(); + // Ensure the inspector selection is still BOTTOM (not TOP). expect( paragraphText( WidgetInspectorService.instance.selection.current! as RenderParagraph, @@ -469,7 +552,8 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( - selectButtonBuilder: null, + exitWidgetSelectionButtonBuilder: null, + moveExitWidgetSelectionButtonBuilder: null, child: Transform( transform: Matrix4.identity()..scale(0.0), child: const Stack( @@ -490,12 +574,21 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { }); testWidgets('WidgetInspector scroll test', (WidgetTester tester) async { - final Key childKey = UniqueKey(); - final GlobalKey selectButtonKey = GlobalKey(); - final GlobalKey inspectorKey = GlobalKey(); + // Enable widget selection mode. + WidgetInspectorService.instance.isSelectMode = true; - Widget selectButtonBuilder(BuildContext context, VoidCallback onPressed) { - return Material(child: ElevatedButton(onPressed: onPressed, key: selectButtonKey, child: null)); + final Key childKey = UniqueKey(); + final GlobalKey inspectorKey = GlobalKey(); + late GlobalKey exitWidgetSelectionButtonKey; + + Widget exitWidgetSelectionButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + required GlobalKey key, + }) { + exitWidgetSelectionButtonKey = key; + return Material( + child: ElevatedButton(onPressed: onPressed, key: key, child: null)); } await tester.pumpWidget( @@ -503,7 +596,8 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { textDirection: TextDirection.ltr, child: WidgetInspector( key: inspectorKey, - selectButtonBuilder: selectButtonBuilder, + exitWidgetSelectionButtonBuilder: exitWidgetSelectionButtonBuilder, + moveExitWidgetSelectionButtonBuilder: null, child: ListView( dragStartBehavior: DragStartBehavior.down, children: [ @@ -534,7 +628,11 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { await tester.pump(); expect(WidgetInspectorService.instance.selection.current, isNotNull); - // Now out of inspect mode due to the click. + // Now exit selection mode by tapping the Exit Selection Mode button. + await tester.tap(find.byKey(exitWidgetSelectionButtonKey)); + await tester.pump(); + + // Now out of inspect mode due to clicking the Exit Selection Mode button. await tester.fling(find.byType(ListView), const Offset(0.0, -200.0), 200.0); await tester.pump(); @@ -547,13 +645,17 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { }); testWidgets('WidgetInspector long press', (WidgetTester tester) async { + // Enable widget selection mode. + WidgetInspectorService.instance.isSelectMode = true; + bool didLongPress = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( - selectButtonBuilder: null, + exitWidgetSelectionButtonBuilder: null, + moveExitWidgetSelectionButtonBuilder: null, child: GestureDetector( onLongPress: () { expect(didLongPress, isFalse); @@ -571,6 +673,9 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { }); testWidgets('WidgetInspector offstage', (WidgetTester tester) async { + // Enable widget selection mode. + WidgetInspectorService.instance.isSelectMode = true; + final GlobalKey inspectorKey = GlobalKey(); final GlobalKey clickTarget = GlobalKey(); @@ -601,7 +706,8 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { textDirection: TextDirection.ltr, child: WidgetInspector( key: inspectorKey, - selectButtonBuilder: null, + exitWidgetSelectionButtonBuilder: null, + moveExitWidgetSelectionButtonBuilder: null, child: Overlay( initialEntries: [ entry1 = OverlayEntry( @@ -642,6 +748,9 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { }); testWidgets('WidgetInspector with Transform above', (WidgetTester tester) async { + // Enable widget selection mode. + WidgetInspectorService.instance.isSelectMode = true; + final GlobalKey childKey = GlobalKey(); final GlobalKey repaintBoundaryKey = GlobalKey(); @@ -660,7 +769,8 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { child: Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( - selectButtonBuilder: null, + exitWidgetSelectionButtonBuilder: null, + moveExitWidgetSelectionButtonBuilder: null, child: ColoredBox( color: Colors.white, child: Center( @@ -689,6 +799,9 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { }); testWidgets('Multiple widget inspectors', (WidgetTester tester) async { + // Enable widget selection mode. + WidgetInspectorService.instance.isSelectMode = true; + // This test verifies that interacting with different inspectors // works correctly. This use case may be an app that displays multiple // apps inside (i.e. a storyboard). @@ -701,8 +814,13 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { final GlobalKey child1Key = GlobalKey(); final GlobalKey child2Key = GlobalKey(); - InspectorSelectButtonBuilder selectButtonBuilder(Key key) { - return (BuildContext context, VoidCallback onPressed) { + ExitWidgetSelectionButtonBuilder exitWidgetSelectionButtonBuilder( + Key key) { + return ( + BuildContext context, { + required VoidCallback onPressed, + required GlobalKey key, + }) { return Material(child: ElevatedButton(onPressed: onPressed, key: key, child: null)); }; } @@ -720,7 +838,9 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { Flexible( child: WidgetInspector( key: inspector1Key, - selectButtonBuilder: selectButtonBuilder(selectButton1Key), + exitWidgetSelectionButtonBuilder: + exitWidgetSelectionButtonBuilder(selectButton1Key), + moveExitWidgetSelectionButtonBuilder: null, child: Container( key: child1Key, child: const Text('Child 1'), @@ -730,7 +850,9 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { Flexible( child: WidgetInspector( key: inspector2Key, - selectButtonBuilder: selectButtonBuilder(selectButton2Key), + exitWidgetSelectionButtonBuilder: + exitWidgetSelectionButtonBuilder(selectButton2Key), + moveExitWidgetSelectionButtonBuilder: null, child: Container( key: child2Key, child: const Text('Child 2'), @@ -751,10 +873,6 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { equals('Child 1'), ); - // Re-enable select mode since it's state is shared between the - // WidgetInspectors - WidgetInspectorService.instance.isSelectMode.value = true; - await tester.tap(find.text('Child 2'), warnIfMissed: false); await tester.pump(); expect( @@ -766,14 +884,20 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { }); testWidgets( - 'WidgetInspector selectButton inspection for tap', + 'WidgetInspector Exit Selection Mode button', (WidgetTester tester) async { - final GlobalKey selectButtonKey = GlobalKey(); + // Enable widget selection mode. + WidgetInspectorService.instance.isSelectMode = true; + final GlobalKey inspectorKey = GlobalKey(); setupDefaultPubRootDirectory(service); - Widget selectButtonBuilder(BuildContext context, VoidCallback onPressed) { - return Material(child: ElevatedButton(onPressed: onPressed, key: selectButtonKey, child: null)); + Widget exitWidgetSelectionButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + required GlobalKey key, + }) { + return Material(child: ElevatedButton(onPressed: onPressed, key: key, child: null)); } await tester.pumpWidget( @@ -781,7 +905,8 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { textDirection: TextDirection.ltr, child: WidgetInspector( key: inspectorKey, - selectButtonBuilder: selectButtonBuilder, + exitWidgetSelectionButtonBuilder: exitWidgetSelectionButtonBuilder, + moveExitWidgetSelectionButtonBuilder: null, child: const Text('Child 1'), ), ), @@ -815,6 +940,94 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { skip: !WidgetInspectorService.instance.isWidgetCreationTracked() // [intended] Test requires --track-widget-creation flag. ); + testWidgets( + 'WidgetInspector Move Exit Selection Mode button to the right / left', + (WidgetTester tester) async { + // Enable widget selection mode. + WidgetInspectorService.instance.isSelectMode = true; + + final GlobalKey inspectorKey = GlobalKey(); + setupDefaultPubRootDirectory(service); + + Widget exitWidgetSelectionButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + required GlobalKey key, + }) { + return Material( + child: ElevatedButton( + onPressed: onPressed, + key: key, + child: const Text('EXIT SELECT MODE'), + ), + ); + } + + Widget moveWidgetSelectionButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + bool isLeftAligned = true, + }) { + return Material( + child: ElevatedButton( + onPressed: onPressed, + child: Text(isLeftAligned ? 'MOVE RIGHT' : 'MOVE LEFT'), + ), + ); + } + + Finder buttonFinder(String buttonText) { + return find.ancestor( + of: find.text(buttonText), + matching: find.byType(ElevatedButton), + ); + } + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WidgetInspector( + key: inspectorKey, + exitWidgetSelectionButtonBuilder: exitWidgetSelectionButtonBuilder, + moveExitWidgetSelectionButtonBuilder: + moveWidgetSelectionButtonBuilder, + child: const Text('APP'), + ), + ), + ); + + // Initially the exit select button is on the left. + final Finder exitButton = buttonFinder('EXIT SELECT MODE'); + expect(exitButton, findsOneWidget); + final Finder moveRightButton = buttonFinder('MOVE RIGHT'); + expect(moveRightButton, findsOneWidget); + final double initialExitButtonX = tester.getCenter(exitButton).dx; + + // Move the button to the right. + await tester.tap(moveRightButton); + await tester.pump(); + + // Verify the button is now on the right. + expect(moveRightButton, findsNothing); + final Finder moveLeftButton = buttonFinder('MOVE LEFT'); + expect(moveLeftButton, findsOneWidget); + final double exitButtonXAfterMovingRight = + tester.getCenter(exitButton).dx; + expect(initialExitButtonX, lessThan(exitButtonXAfterMovingRight)); + + // Move the button to the left again. + await tester.tap(moveLeftButton); + await tester.pump(); + + // Verify the button is in its original position. + expect(moveLeftButton, findsNothing); + expect(moveRightButton, findsOneWidget); + final double exitButtonXAfterMovingLeft = tester.getCenter(exitButton).dx; + expect(exitButtonXAfterMovingLeft, equals(initialExitButtonX)); + }, + skip: !WidgetInspectorService.instance.isWidgetCreationTracked() // [intended] Test requires --track-widget-creation flag. + ); + testWidgets('test transformDebugCreator will re-order if after stack trace', (WidgetTester tester) async { final bool widgetTracked = WidgetInspectorService.instance.isWidgetCreationTracked(); await tester.pumpWidget( @@ -1964,7 +2177,7 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { /// Gets the children nodes from the JSON response. List childrenFromJsonResponse(Map json) { - return json['children']! as List; + return (json['children'] as List?) ?? []; } /// Gets the children nodes using a call to @@ -2358,7 +2571,6 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { ), isTrue, ); - expect( allChildrenSatisfyCondition(rootJson, condition: wasCreatedByLocalProject, @@ -3727,7 +3939,8 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { final Widget widget = Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( - selectButtonBuilder: null, + exitWidgetSelectionButtonBuilder: null, + moveExitWidgetSelectionButtonBuilder: null, child: _applyConstructor(_TrivialWidget.new), ), ); @@ -5544,7 +5757,6 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { node.toJsonMap(const DiagnosticsSerializationDelegate()), equals({ 'description': 'description of the deep link', - 'shouldIndent': true, 'type': 'DevToolsDeepLinkProperty', 'name': '', 'style': 'singleLine', diff --git a/packages/flutter/test_private/pubspec.yaml b/packages/flutter/test_private/pubspec.yaml index 488efbba65f..db3b7b73e31 100644 --- a/packages/flutter/test_private/pubspec.yaml +++ b/packages/flutter/test_private/pubspec.yaml @@ -2,7 +2,7 @@ name: flutter_test_private description: Tests private interfaces of the flutter environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: # To update these, use "flutter update-packages --force-upgrade". diff --git a/packages/flutter/test_private/test/pubspec.yaml b/packages/flutter/test_private/test/pubspec.yaml index 93b3bebbf67..8ea28f2963b 100644 --- a/packages/flutter/test_private/test/pubspec.yaml +++ b/packages/flutter/test_private/test/pubspec.yaml @@ -1,7 +1,7 @@ name: animated_icons_private_test environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: # To update these, use "flutter update-packages --force-upgrade". diff --git a/packages/flutter_driver/lib/src/common/screenshot.dart b/packages/flutter_driver/lib/src/common/screenshot.dart index 851c8514e2f..0fc05328ab3 100644 --- a/packages/flutter_driver/lib/src/common/screenshot.dart +++ b/packages/flutter_driver/lib/src/common/screenshot.dart @@ -58,7 +58,7 @@ class ScreenshotCommand extends Command { /// base64 encode a PNG class ScreenshotResult extends Result { - /// Consructs a screenshot result with PNG or raw RGBA byte data. + /// Constructs a screenshot result with PNG or raw RGBA byte data. ScreenshotResult(this._data); final Uint8List _data; diff --git a/packages/flutter_driver/pubspec.yaml b/packages/flutter_driver/pubspec.yaml index 528da1003f6..44b53c941c1 100644 --- a/packages/flutter_driver/pubspec.yaml +++ b/packages/flutter_driver/pubspec.yaml @@ -3,7 +3,7 @@ description: Integration and performance test API for Flutter applications homepage: https://flutter.dev environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: file: 7.0.1 diff --git a/packages/flutter_goldens/pubspec.yaml b/packages/flutter_goldens/pubspec.yaml index 8ddf2ad0464..4ed7449a12d 100644 --- a/packages/flutter_goldens/pubspec.yaml +++ b/packages/flutter_goldens/pubspec.yaml @@ -1,7 +1,7 @@ name: flutter_goldens environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: # To update these, use "flutter update-packages --force-upgrade". diff --git a/packages/flutter_localizations/lib/src/l10n/generated_material_localizations.dart b/packages/flutter_localizations/lib/src/l10n/generated_material_localizations.dart index 5895328f48f..49744613a61 100644 --- a/packages/flutter_localizations/lib/src/l10n/generated_material_localizations.dart +++ b/packages/flutter_localizations/lib/src/l10n/generated_material_localizations.dart @@ -18612,7 +18612,7 @@ class MaterialLocalizationHi extends GlobalMaterialLocalizations { String get tabLabelRaw => r'$tabCount का टैब $tabIndex'; @override - TimeOfDayFormat get timeOfDayFormatRaw => TimeOfDayFormat.a_space_h_colon_mm; + TimeOfDayFormat get timeOfDayFormatRaw => TimeOfDayFormat.h_colon_mm_space_a; @override String get timePickerDialHelpText => 'समय चुनें'; diff --git a/packages/flutter_localizations/lib/src/l10n/material_hi.arb b/packages/flutter_localizations/lib/src/l10n/material_hi.arb index 1489b1fb303..96f1b5de1f7 100644 --- a/packages/flutter_localizations/lib/src/l10n/material_hi.arb +++ b/packages/flutter_localizations/lib/src/l10n/material_hi.arb @@ -1,6 +1,6 @@ { "scriptCategory": "dense", - "timeOfDayFormat": "ah:mm", + "timeOfDayFormat": "h:mm a", "openAppDrawerTooltip": "नेविगेशन मेन्यू खोलें", "backButtonTooltip": "वापस जाएं", "closeButtonTooltip": "बंद करें", diff --git a/packages/flutter_localizations/pubspec.yaml b/packages/flutter_localizations/pubspec.yaml index 4860a2d89e5..3f339f46f5e 100644 --- a/packages/flutter_localizations/pubspec.yaml +++ b/packages/flutter_localizations/pubspec.yaml @@ -1,7 +1,7 @@ name: flutter_localizations environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: # To update these, use "flutter update-packages --force-upgrade". diff --git a/packages/flutter_localizations/test/material/time_picker_test.dart b/packages/flutter_localizations/test/material/time_picker_test.dart index 573a0548874..9efa573f55b 100644 --- a/packages/flutter_localizations/test/material/time_picker_test.dart +++ b/packages/flutter_localizations/test/material/time_picker_test.dart @@ -603,6 +603,38 @@ void main() { labels00To22TwoDigit, ); }); + + // Regression test for https://github.com/flutter/flutter/issues/156565 + testWidgets('AM/PM buttons should be aligned to LTR in Hindi language - Portrait', (WidgetTester tester) async { + const Locale locale = Locale('hi', 'HI'); + + final Offset centerPortrait = await startPicker(tester, (TimeOfDay? time) {}, locale: locale, useMaterial3: false, orientation: Orientation.portrait); + + final Finder amButtonPortrait = find.text('AM'); + final Finder pmButtonPortrait = find.text('PM') ; + + final Offset amButtonPositionPortrait = tester.getCenter(amButtonPortrait); + final Offset pmButtonPositionPortrait = tester.getCenter(pmButtonPortrait); + + expect(amButtonPositionPortrait.dx, greaterThan(centerPortrait.dx)); + expect(pmButtonPositionPortrait.dx, greaterThan(centerPortrait.dx)); + }); + + // Regression test for https://github.com/flutter/flutter/issues/156565 + testWidgets('AM/PM buttons should be aligned to LTR in Hindi language - Landscape', (WidgetTester tester) async { + const Locale locale = Locale('hi', 'HI'); + + final Offset centerLandscape = await startPicker(tester, (TimeOfDay? time) {}, locale: locale, useMaterial3: false, orientation: Orientation.landscape); + + final Finder amButtonLandscape = find.text('AM'); + final Finder pmButtonLandscape = find.text('PM'); + + final Offset amButtonPositionLandscape = tester.getCenter(amButtonLandscape); + final Offset pmButtonPositionLandscape = tester.getCenter(pmButtonLandscape); + + expect(amButtonPositionLandscape.dy, greaterThan(centerLandscape.dy)); + expect(pmButtonPositionLandscape.dy, greaterThan(centerLandscape.dy)); + }); } class _TimePickerLauncher extends StatelessWidget { @@ -611,12 +643,14 @@ class _TimePickerLauncher extends StatelessWidget { required this.locale, this.entryMode = TimePickerEntryMode.dial, this.useMaterial3, + this.orientation, }); final ValueChanged? onChanged; final Locale locale; final TimePickerEntryMode entryMode; final bool? useMaterial3; + final Orientation? orientation; @override Widget build(BuildContext context) { @@ -635,6 +669,7 @@ class _TimePickerLauncher extends StatelessWidget { onChanged?.call(await showTimePicker( context: context, initialEntryMode: entryMode, + orientation: orientation, initialTime: const TimeOfDay(hour: 7, minute: 0), )); }, @@ -652,12 +687,14 @@ Future startPicker( ValueChanged onChanged, { Locale locale = const Locale('en', 'US'), bool? useMaterial3, + Orientation? orientation, }) async { await tester.pumpWidget( _TimePickerLauncher( onChanged: onChanged, locale: locale, useMaterial3: useMaterial3, + orientation: orientation, ), ); await tester.tap(find.text('X')); diff --git a/packages/flutter_test/lib/src/controller.dart b/packages/flutter_test/lib/src/controller.dart index 069da72fa4f..5e495bab1df 100644 --- a/packages/flutter_test/lib/src/controller.dart +++ b/packages/flutter_test/lib/src/controller.dart @@ -71,7 +71,8 @@ class SemanticsController { SemanticsAction.scrollUp.index | SemanticsAction.scrollDown.index | SemanticsAction.scrollLeft.index | - SemanticsAction.scrollRight.index; + SemanticsAction.scrollRight.index | + SemanticsAction.scrollToOffset.index; /// Based on Android's FOCUSABLE_FLAGS. See [flutter/engine/AccessibilityBridge.java](https://github.com/flutter/engine/blob/main/shell/platform/android/io/flutter/view/AccessibilityBridge.java). static final int _importantFlagsForAccessibility = @@ -322,7 +323,7 @@ class SemanticsController { /// Recursive depth first traversal of the specified `node`, adding nodes /// that are important for semantics to the `traversal` list. - void _accessibilityTraversal(SemanticsNode node, List traversal){ + void _accessibilityTraversal(SemanticsNode node, List traversal) { if (_isImportantForAccessibility(node)) { traversal.add(node); } @@ -381,10 +382,10 @@ class SemanticsController { finders.FinderBase finder, SemanticsAction action, { Object? args, - bool checkForAction = true + bool checkForAction = true, }) { final SemanticsNode node = finder.evaluate().single; - if (checkForAction && !node.getSemanticsData().hasAction(action)){ + if (checkForAction && !node.getSemanticsData().hasAction(action)) { throw StateError( 'The given node does not support $action. If the action is implicitly ' 'supported or an unsupported action is being tested for this node, ' @@ -515,12 +516,12 @@ class SemanticsController { /// [SemanticsAction.moveCursorForwardByCharacter]. void moveCursorForwardByCharacter( finders.FinderBase finder, { - bool shouldModifySelection = false + bool shouldModifySelection = false, }) { performAction( finder, SemanticsAction.moveCursorForwardByCharacter, - args: shouldModifySelection + args: shouldModifySelection, ); } @@ -533,12 +534,12 @@ class SemanticsController { /// [SemanticsAction.moveCursorForwardByWord]. void moveCursorForwardByWord( finders.FinderBase finder, { - bool shouldModifySelection = false + bool shouldModifySelection = false, }) { performAction( finder, SemanticsAction.moveCursorForwardByWord, - args: shouldModifySelection + args: shouldModifySelection, ); } @@ -554,12 +555,12 @@ class SemanticsController { /// [SemanticsAction.moveCursorBackwardByCharacter]. void moveCursorBackwardByCharacter( finders.FinderBase finder, { - bool shouldModifySelection = false + bool shouldModifySelection = false, }) { performAction( finder, SemanticsAction.moveCursorBackwardByCharacter, - args: shouldModifySelection + args: shouldModifySelection, ); } @@ -572,12 +573,12 @@ class SemanticsController { /// [SemanticsAction.moveCursorBackwardByWord]. void moveCursorBackwardByWord( finders.FinderBase finder, { - bool shouldModifySelection = false + bool shouldModifySelection = false, }) { performAction( finder, SemanticsAction.moveCursorBackwardByWord, - args: shouldModifySelection + args: shouldModifySelection, ); } @@ -606,7 +607,7 @@ class SemanticsController { void setSelection( finders.FinderBase finder, { required int base, - required int extent + required int extent, }) { performAction( finder, @@ -681,7 +682,7 @@ class SemanticsController { performAction( finder, SemanticsAction.customAction, - args: CustomSemanticsAction.getIdentifier(action) + args: CustomSemanticsAction.getIdentifier(action), ); } @@ -1000,6 +1001,7 @@ abstract class WidgetController { ..._walkLayers(renderView.debugLayer!) ]; } + Iterable _walkLayers(Layer layer) sync* { TestAsyncUtils.guardSync(); yield layer; @@ -1059,7 +1061,7 @@ abstract class WidgetController { /// /// The `pointer` and `button` arguments specify [PointerEvent.pointer] and /// [PointerEvent.buttons] of the tap event. - Future tapOnText(finders.FinderBase textRangeFinder, {int? pointer, int buttons = kPrimaryButton }) { + Future tapOnText(finders.FinderBase textRangeFinder, { int? pointer, int buttons = kPrimaryButton }) { final Iterable ranges = textRangeFinder.evaluate(); if (ranges.isEmpty) { throw FlutterError(textRangeFinder.toString()); @@ -1073,13 +1075,12 @@ abstract class WidgetController { if (tapLocation == null) { final finders.TextRangeContext found = textRangeFinder.evaluate().single; throw FlutterError.fromParts([ - ErrorSummary('Finder specifies a TextRange that can not receive pointer events.'), - ErrorDescription('The finder used was: ${textRangeFinder.toString(describeSelf: true)}'), - ErrorDescription('Found a matching substring in a static text widget, within ${found.textRange}.'), - ErrorDescription('But the "tapOnText" method could not find a hit-testable Offset with in that text range.'), - found.renderObject.toDiagnosticsNode(name: 'The RenderBox of that static text widget was', style: DiagnosticsTreeStyle.shallow), - ] - ); + ErrorSummary('Finder specifies a TextRange that can not receive pointer events.'), + ErrorDescription('The finder used was: ${textRangeFinder.toString(describeSelf: true)}'), + ErrorDescription('Found a matching substring in a static text widget, within ${found.textRange}.'), + ErrorDescription('But the "tapOnText" method could not find a hit-testable Offset with in that text range.'), + found.renderObject.toDiagnosticsNode(name: 'The RenderBox of that static text widget was', style: DiagnosticsTreeStyle.shallow), + ]); } return tapAt(tapLocation, pointer: pointer, buttons: buttons); } @@ -1643,22 +1644,22 @@ abstract class WidgetController { ]; final List records = [ PointerEventRecord(Duration.zero, [ - PointerAddedEvent( - position: startLocation, - ), - PointerDownEvent( - position: startLocation, - pointer: pointer, - buttons: buttons, - ), - ]), + PointerAddedEvent( + position: startLocation, + ), + PointerDownEvent( + position: startLocation, + pointer: pointer, + buttons: buttons, + ), + ]), ...[ for (int t = 0; t <= intervals; t += 1) PointerEventRecord(timeStamps[t], [ PointerMoveEvent( timeStamp: timeStamps[t], - position: offsets[t+1], - delta: offsets[t+1] - offsets[t], + position: offsets[t + 1], + delta: offsets[t + 1] - offsets[t], pointer: pointer, buttons: buttons, ), @@ -1993,7 +1994,7 @@ abstract class WidgetController { LogicalKeyboardKey key, { String? platform, String? character, - PhysicalKeyboardKey? physicalKey + PhysicalKeyboardKey? physicalKey, }) async { final bool handled = await simulateKeyDownEvent(key, platform: platform, character: character, physicalKey: physicalKey); // Internally wrapped in async guard. @@ -2032,7 +2033,7 @@ abstract class WidgetController { LogicalKeyboardKey key, { String? platform, String? character, - PhysicalKeyboardKey? physicalKey + PhysicalKeyboardKey? physicalKey, }) async { // Internally wrapped in async guard. return simulateKeyDownEvent(key, platform: platform, character: character, physicalKey: physicalKey); @@ -2060,10 +2061,10 @@ abstract class WidgetController { /// corresponding key down and repeat event. /// - [sendKeyEvent] to simulate both the key up and key down in the same call. Future sendKeyUpEvent( - LogicalKeyboardKey key, { - String? platform, - PhysicalKeyboardKey? physicalKey - }) async { + LogicalKeyboardKey key, { + String? platform, + PhysicalKeyboardKey? physicalKey, + }) async { // Internally wrapped in async guard. return simulateKeyUpEvent(key, platform: platform, physicalKey: physicalKey); } @@ -2096,11 +2097,11 @@ abstract class WidgetController { /// key down and up event. /// - [sendKeyEvent] to simulate both the key up and key down in the same call. Future sendKeyRepeatEvent( - LogicalKeyboardKey key, { - String? platform, - String? character, - PhysicalKeyboardKey? physicalKey - }) async { + LogicalKeyboardKey key, { + String? platform, + String? character, + PhysicalKeyboardKey? physicalKey, + }) async { // Internally wrapped in async guard. return simulateKeyRepeatEvent(key, platform: platform, character: character, physicalKey: physicalKey); } @@ -2175,11 +2176,10 @@ abstract class WidgetController { Future scrollUntilVisible( finders.FinderBase finder, double delta, { - finders.FinderBase? scrollable, - int maxScrolls = 50, - Duration duration = const Duration(milliseconds: 50), - } - ) { + finders.FinderBase? scrollable, + int maxScrolls = 50, + Duration duration = const Duration(milliseconds: 50), + }) { assert(maxScrolls > 0); scrollable ??= finders.find.byType(Scrollable); return TestAsyncUtils.guard(() async { @@ -2219,8 +2219,8 @@ abstract class WidgetController { finders.FinderBase finder, finders.FinderBase view, Offset moveStep, { - int maxIteration = 50, - Duration duration = const Duration(milliseconds: 50), + int maxIteration = 50, + Duration duration = const Duration(milliseconds: 50), }) { return TestAsyncUtils.guard(() async { while (maxIteration > 0 && finder.evaluate().isEmpty) { diff --git a/packages/flutter_test/pubspec.yaml b/packages/flutter_test/pubspec.yaml index 2b351443cd8..bb43605e67d 100644 --- a/packages/flutter_test/pubspec.yaml +++ b/packages/flutter_test/pubspec.yaml @@ -1,7 +1,7 @@ name: flutter_test environment: - sdk: '>=3.3.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: # To update these, use "flutter update-packages --force-upgrade". diff --git a/packages/flutter_test/test/bindings_test.dart b/packages/flutter_test/test/bindings_test.dart index 5a789fdc323..5425b7d92c2 100644 --- a/packages/flutter_test/test/bindings_test.dart +++ b/packages/flutter_test/test/bindings_test.dart @@ -30,6 +30,11 @@ void main() { final Matrix4 matrix = TestViewConfiguration(size: Size.zero).toMatrix(); expect(matrix.storage.every((double x) => x.isFinite), isTrue); }); + + test('sets the DPR to match the window', () { + final TestViewConfiguration configuration = TestViewConfiguration(size: const Size(1280.0, 800.0)); + expect(configuration.devicePixelRatio, binding.window.devicePixelRatio); + }); }); group(AutomatedTestWidgetsFlutterBinding, () { diff --git a/packages/flutter_test/test/test_config/project_root/pubspec.yaml b/packages/flutter_test/test/test_config/project_root/pubspec.yaml index 75c96b122fe..e5d81182ba0 100644 --- a/packages/flutter_test/test/test_config/project_root/pubspec.yaml +++ b/packages/flutter_test/test/test_config/project_root/pubspec.yaml @@ -4,6 +4,6 @@ name: dummy environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 # PUBSPEC CHECKSUM: 0000 diff --git a/packages/flutter_tools/bin/fuchsia_asset_builder.dart b/packages/flutter_tools/bin/fuchsia_asset_builder.dart index 8f2d840ba0c..0faf758b671 100644 --- a/packages/flutter_tools/bin/fuchsia_asset_builder.dart +++ b/packages/flutter_tools/bin/fuchsia_asset_builder.dart @@ -16,7 +16,7 @@ import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/context_runner.dart'; import 'package:flutter_tools/src/dart/package_map.dart'; import 'package:flutter_tools/src/globals.dart' as globals; -import 'package:flutter_tools/src/reporting/reporting.dart'; +import 'package:unified_analytics/unified_analytics.dart'; const String _kOptionPackages = 'packages'; const String _kOptionAsset = 'asset-dir'; @@ -33,8 +33,8 @@ const List _kRequiredOptions = [ Future main(List args) { return runInContext(() => run(args), overrides: { - Usage: () => DisabledUsage(), - }, useImplicitPubspecResolution: true); + Analytics: () => const NoOpAnalytics(), + }); } Future writeAssetFile(libfs.File outputFile, AssetBundleEntry asset) async { diff --git a/packages/flutter_tools/bin/fuchsia_tester.dart b/packages/flutter_tools/bin/fuchsia_tester.dart index fd86402f31f..61e4dceea3b 100644 --- a/packages/flutter_tools/bin/fuchsia_tester.dart +++ b/packages/flutter_tools/bin/fuchsia_tester.dart @@ -18,10 +18,10 @@ import 'package:flutter_tools/src/device.dart'; import 'package:flutter_tools/src/globals.dart' as globals; import 'package:flutter_tools/src/isolated/native_assets/test/native_assets.dart'; import 'package:flutter_tools/src/project.dart'; -import 'package:flutter_tools/src/reporting/reporting.dart'; import 'package:flutter_tools/src/test/coverage_collector.dart'; import 'package:flutter_tools/src/test/runner.dart'; import 'package:flutter_tools/src/test/test_wrapper.dart'; +import 'package:unified_analytics/unified_analytics.dart'; const String _kOptionPackages = 'packages'; const String _kOptionShell = 'shell'; @@ -42,8 +42,8 @@ const String _kOptionCoveragePath = 'coverage-path'; void main(List args) { runInContext(() => run(args), overrides: { - Usage: () => DisabledUsage(), - }, useImplicitPubspecResolution: true); + Analytics: () => const NoOpAnalytics(), + }); } Future run(List args) async { diff --git a/packages/flutter_tools/bin/macos_assemble.sh b/packages/flutter_tools/bin/macos_assemble.sh index a7f05d91138..77835638e61 100755 --- a/packages/flutter_tools/bin/macos_assemble.sh +++ b/packages/flutter_tools/bin/macos_assemble.sh @@ -218,7 +218,7 @@ EmbedFrameworks() { fi local native_assets_path="${project_path}/${FLUTTER_BUILD_DIR}/native_assets/macos/" if [[ -d "$native_assets_path" ]]; then - RunCommand rsync -av --filter "- .DS_Store" --filter "- native_assets.yaml" "${native_assets_path}" "${xcode_frameworks_dir}" + RunCommand rsync -av --filter "- .DS_Store" --filter "- native_assets.yaml" --filter "- native_assets.json" "${native_assets_path}" "${xcode_frameworks_dir}" # Iterate through all .frameworks in native assets directory. for native_asset in "${native_assets_path}"*.framework; do diff --git a/packages/flutter_tools/bin/podhelper.rb b/packages/flutter_tools/bin/podhelper.rb index 64e163ea85d..008dc64fe7b 100644 --- a/packages/flutter_tools/bin/podhelper.rb +++ b/packages/flutter_tools/bin/podhelper.rb @@ -304,7 +304,7 @@ def flutter_install_plugin_pods(application_path = nil, relative_symlink_dir, pl plugins_file = File.join(application_path, '..', '.flutter-plugins-dependencies') dependencies_hash = flutter_parse_plugins_file(plugins_file) plugin_pods = flutter_get_plugins_list(dependencies_hash, platform) - swift_package_manager_enabled = flutter_get_swift_package_manager_enabled(dependencies_hash) + swift_package_manager_enabled = flutter_get_swift_package_manager_enabled(dependencies_hash, platform) plugin_pods.each do |plugin_hash| plugin_name = plugin_hash['name'] @@ -353,10 +353,12 @@ def flutter_get_plugins_list(dependencies_hash, platform) dependencies_hash['plugins'][platform] || [] end -def flutter_get_swift_package_manager_enabled(dependencies_hash) +def flutter_get_swift_package_manager_enabled(dependencies_hash, platform) return false unless dependencies_hash.any? return false unless dependencies_hash.has_key?('swift_package_manager_enabled') - dependencies_hash['swift_package_manager_enabled'] == true + return false unless dependencies_hash['swift_package_manager_enabled'].has_key?(platform) + + dependencies_hash['swift_package_manager_enabled'][platform] == true end def flutter_relative_path_from_podfile(path) diff --git a/packages/flutter_tools/bin/xcode_backend.dart b/packages/flutter_tools/bin/xcode_backend.dart index d0d39df86ed..d517bead965 100644 --- a/packages/flutter_tools/bin/xcode_backend.dart +++ b/packages/flutter_tools/bin/xcode_backend.dart @@ -245,6 +245,8 @@ class Context { extraArgs: [ '--filter', '- native_assets.yaml', + '--filter', + '- native_assets.json', ], nativeAssetsPath, xcodeFrameworksDir, diff --git a/packages/flutter_tools/dart_test.yaml b/packages/flutter_tools/dart_test.yaml index f437c0fdb2c..c4e8817b639 100644 --- a/packages/flutter_tools/dart_test.yaml +++ b/packages/flutter_tools/dart_test.yaml @@ -16,3 +16,9 @@ tags: # the --test-randomize-ordering-seed for the suites that have this tag. no-shuffle: allow_test_randomization: false + + # Tests that invoke `flutter build apk` for integration. + flutter-build-apk: {} + + # Tests that invoke `flutter test ...` or `flutter run ...` for integration. + flutter-test-driver: {} diff --git a/packages/flutter_tools/gradle/aar_init_script.gradle b/packages/flutter_tools/gradle/aar_init_script.gradle index aa6bac1a39e..d2c47259e4d 100644 --- a/packages/flutter_tools/gradle/aar_init_script.gradle +++ b/packages/flutter_tools/gradle/aar_init_script.gradle @@ -4,16 +4,14 @@ // The local repository will contain the AAR and POM files. import java.nio.file.Paths -import org.gradle.api.Project -import org.gradle.api.artifacts.Configuration -import org.gradle.api.publish.maven.MavenPublication + void configureProject(Project project, String outputDir) { if (!project.hasProperty("android")) { throw new GradleException("Android property not found.") } if (!project.android.hasProperty("libraryVariants")) { - throw new GradleException("Can't generate AAR on a non Android library project."); + throw new GradleException("Can't generate AAR on a non Android library project.") } // Snapshot versions include the timestamp in the artifact name. @@ -79,7 +77,7 @@ void configurePlugin(Project project, String outputDir) { configureProject(project, outputDir) } -String getFlutterRoot(Project project) { +static String getFlutterRoot(Project project) { if (!project.hasProperty("flutter-root")) { throw new GradleException("The `-Pflutter-root` flag must be specified.") } @@ -157,6 +155,10 @@ projectsEvaluated { configureProject(rootProject, rootProject.property("output-dir")) return } + if (rootProject.name == "gradle") { + // Skip the "gradle" project, we are looking only for the "android_generated" project. + return + } // The module project is the `:flutter` subproject. Project moduleProject = rootProject.subprojects.find { it.name == "flutter" } assert moduleProject != null diff --git a/packages/flutter_tools/gradle/build.gradle.kts b/packages/flutter_tools/gradle/build.gradle.kts index ebe4216b454..5a43386eae9 100644 --- a/packages/flutter_tools/gradle/build.gradle.kts +++ b/packages/flutter_tools/gradle/build.gradle.kts @@ -4,7 +4,7 @@ plugins { `java-gradle-plugin` - `groovy` + groovy } group = "dev.flutter.plugin" diff --git a/packages/flutter_tools/gradle/module_plugin_loader.gradle b/packages/flutter_tools/gradle/module_plugin_loader.gradle index f22dffbd823..98ffc28ba7a 100644 --- a/packages/flutter_tools/gradle/module_plugin_loader.gradle +++ b/packages/flutter_tools/gradle/module_plugin_loader.gradle @@ -26,7 +26,7 @@ gradle.getGradle().projectsLoaded { g -> p.subprojects { subproject -> if (nativePlugins.name.contains(subproject.name)) { File androidPluginBuildOutputDir = new File(flutterModulePath + File.separator - + "plugins_build_output" + File.separator + subproject.name); + + "plugins_build_output" + File.separator + subproject.name) if (!androidPluginBuildOutputDir.exists()) { androidPluginBuildOutputDir.mkdirs() } diff --git a/packages/flutter_tools/gradle/resolve_dependencies.gradle b/packages/flutter_tools/gradle/resolve_dependencies.gradle index 6355654f2ed..65b53fdbd35 100644 --- a/packages/flutter_tools/gradle/resolve_dependencies.gradle +++ b/packages/flutter_tools/gradle/resolve_dependencies.gradle @@ -19,7 +19,7 @@ String storageUrl = System.getenv('FLUTTER_STORAGE_BASE_URL') ?: "https://storag String engineRealm = Paths.get(flutterRoot.absolutePath, "bin", "internal", "engine.realm") .toFile().text.trim() if (engineRealm) { - engineRealm = engineRealm + "/" + engineRealm += "/" } repositories { @@ -58,7 +58,7 @@ dependencies { flutterDebug "io.flutter:x86_64_debug:1.0.0-$engineVersion" } -task resolveDependencies { +tasks.register('resolveDependencies') { configurations.each { configuration -> if (configuration.name.startsWith("flutter")) { configuration.resolve() diff --git a/packages/flutter_tools/gradle/src/main/groovy/flutter.groovy b/packages/flutter_tools/gradle/src/main/groovy/flutter.groovy index 4949b597fc0..dfec35b704b 100644 --- a/packages/flutter_tools/gradle/src/main/groovy/flutter.groovy +++ b/packages/flutter_tools/gradle/src/main/groovy/flutter.groovy @@ -26,6 +26,7 @@ import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.OutputFiles import org.gradle.api.tasks.Optional import org.gradle.api.tasks.TaskAction +import org.gradle.api.tasks.TaskProvider import org.gradle.api.tasks.bundling.Jar import org.gradle.internal.os.OperatingSystem @@ -677,7 +678,12 @@ class FlutterPlugin implements Plugin { */ private void configureLegacyPluginEachProjects(Project project) { try { - if (!settingsGradleFile(project).text.contains("'.flutter-plugins'")) { + // Read the contents of the settings.gradle file. + // Remove block/line comments + String settingsText = settingsGradleFile(project).text + settingsText = settingsText.replaceAll(/(?s)\/\*.*?\*\//, '').replaceAll(/(?m)\/\/.*$/, '') + + if (!settingsText.contains("'.flutter-plugins'")) { return } } catch (FileNotFoundException ignored) { @@ -763,10 +769,18 @@ class FlutterPlugin implements Plugin { // Apply the "flutter" Gradle extension to plugins so that they can use it's vended // compile/target/min sdk values. pluginProject.extensions.create("flutter", FlutterExtension) + // Add plugin dependency to the app project. - project.dependencies { - api(pluginProject) + project.android.buildTypes.each { buildType -> + String flutterBuildMode = buildModeFor(buildType) + if (flutterBuildMode != "release" || !pluginObject.dev_dependency) { + // Only add dependency on dev dependencies in non-release builds. + project.dependencies { + api(pluginProject) + } + } } + Closure addEmbeddingDependencyToPlugin = { buildType -> String flutterBuildMode = buildModeFor(buildType) // In AGP 3.5, the embedding must be added as an API implementation, @@ -778,6 +792,12 @@ class FlutterPlugin implements Plugin { if (!pluginProject.hasProperty("android")) { return } + if (flutterBuildMode == "release" && pluginObject.dev_dependency) { + // This plugin is a dev dependency and will not be included in + // the release build, so no need to add the embedding + // dependency to it. + return + } // Copy build types from the app to the plugin. // This allows to build apps with plugins and custom build types or flavors. pluginProject.android.buildTypes { @@ -938,20 +958,29 @@ class FlutterPlugin implements Plugin { if (pluginProject == null) { return } - def dependencies = pluginObject.dependencies - assert(dependencies instanceof List) - dependencies.each { pluginDependencyName -> - if (pluginDependencyName.empty) { + + project.android.buildTypes.each { buildType -> + String flutterBuildMode = buildModeFor(buildType) + if (flutterBuildMode == "release" && pluginObject.dev_dependency) { + // This plugin is a dev dependency will not be included in the + // release build, so no need to add its dependencies. return } - Project dependencyProject = project.rootProject.findProject(":$pluginDependencyName") - if (dependencyProject == null) { - return - } - // Wait for the Android plugin to load and add the dependency to the plugin project. - pluginProject.afterEvaluate { - pluginProject.dependencies { - implementation(dependencyProject) + def dependencies = pluginObject.dependencies + assert(dependencies instanceof List) + dependencies.each { pluginDependencyName -> + if (pluginDependencyName.empty) { + return + } + Project dependencyProject = project.rootProject.findProject(":$pluginDependencyName") + if (dependencyProject == null) { + return + } + // Wait for the Android plugin to load and add the dependency to the plugin project. + pluginProject.afterEvaluate { + pluginProject.dependencies { + implementation(dependencyProject) + } } } } @@ -1230,8 +1259,18 @@ class FlutterPlugin implements Plugin { boolean isBuildingAar = project.hasProperty("is-plugin") // In add to app scenarios, a Gradle project contains a `:flutter` and `:app` project. // `:flutter` is used as a subproject when these tasks exists and the build isn't building an AAR. - Task packageAssets = project.tasks.findByPath(":flutter:package${variant.name.capitalize()}Assets") - Task cleanPackageAssets = project.tasks.findByPath(":flutter:cleanPackage${variant.name.capitalize()}Assets") + Task packageAssets + Task cleanPackageAssets + try { + packageAssets = project.tasks.named("package${variant.name.capitalize()}Assets").get() + } catch (UnknownTaskException ignored) { + packageAssets = null + } + try { + cleanPackageAssets = project.tasks.named("cleanPackage${variant.name.capitalize()}Assets").get() + } catch (UnknownTaskException ignored) { + cleanPackageAssets = null + } boolean isUsedAsSubproject = packageAssets && cleanPackageAssets && !isBuildingAar String variantBuildMode = buildModeFor(variant.buildType) @@ -1243,7 +1282,7 @@ class FlutterPlugin implements Plugin { // original value. You either need to hoist the value // into a separate variable `verbose verboseValue` or prefix with // `this` (`verbose this.isVerbose()`). - FlutterTask compileTask = project.tasks.create(name: taskName, type: FlutterTask) { + TaskProvider compileTaskProvider = project.tasks.register(taskName , FlutterTask) { flutterRoot(this.flutterRoot) flutterExecutable(this.flutterExecutable) buildMode(variantBuildMode) @@ -1274,8 +1313,9 @@ class FlutterPlugin implements Plugin { validateDeferredComponents(validateDeferredComponentsValue) flavor(flavorValue) } + Task compileTask = compileTaskProvider.get(); File libJar = project.file(project.layout.buildDirectory.dir("$INTERMEDIATES_DIR/flutter/${variant.name}/libs.jar")) - Task packJniLibsTask = project.tasks.create(name: "packJniLibs${FLUTTER_BUILD_PREFIX}${variant.name.capitalize()}", type: Jar) { + TaskProvider packJniLibsTaskProvider = project.tasks.register("packJniLibs${FLUTTER_BUILD_PREFIX}${variant.name.capitalize()}", Jar) { destinationDirectory = libJar.parentFile archiveFileName = libJar.name dependsOn compileTask @@ -1300,12 +1340,12 @@ class FlutterPlugin implements Plugin { } } } + Task packJniLibsTask = packJniLibsTaskProvider.get(); addApiDependencies(project, variant.name, project.files { packJniLibsTask }) - Task copyFlutterAssetsTask = project.tasks.create( - name: "copyFlutterAssets${variant.name.capitalize()}", - type: Copy, + TaskProvider copyFlutterAssetsTaskProvider = project.tasks.register( + "copyFlutterAssets${variant.name.capitalize()}" , Copy ) { dependsOn(compileTask) with(compileTask.assets) @@ -1339,6 +1379,7 @@ class FlutterPlugin implements Plugin { mergeAssets.mustRunAfter("clean${mergeAssets.name.capitalize()}") into(mergeAssets.outputDir) } + Task copyFlutterAssetsTask = copyFlutterAssetsTaskProvider.get(); if (!isUsedAsSubproject) { def variantOutput = variant.outputs.first() def processResources = variantOutput.hasProperty(propProcessResourcesProvider) ? diff --git a/packages/flutter_tools/gradle/src/main/groovy/native_plugin_loader.groovy b/packages/flutter_tools/gradle/src/main/groovy/native_plugin_loader.groovy index 1ca726ac605..177fb87bbf6 100644 --- a/packages/flutter_tools/gradle/src/main/groovy/native_plugin_loader.groovy +++ b/packages/flutter_tools/gradle/src/main/groovy/native_plugin_loader.groovy @@ -19,9 +19,10 @@ class NativePluginLoader { * "path": "/path/to/plugin-a", * "dependencies": ["plugin-b", "plugin-c"], * "native_build": true + * "dev_dependency": false * } * - * Therefore the map value can either be a `String`, a `List` or a `boolean`. + * Therefore the map value can either be a `String`, a `List` or a `Boolean`. */ List> getPlugins(File flutterSourceDirectory) { List> nativePlugins = [] @@ -40,6 +41,7 @@ class NativePluginLoader { assert(androidPlugin.name instanceof String) assert(androidPlugin.path instanceof String) assert(androidPlugin.dependencies instanceof List) + assert(androidPlugin.dev_dependency instanceof Boolean) // Skip plugins that have no native build (such as a Dart-only implementation // of a federated plugin). def needsBuild = androidPlugin.containsKey(nativeBuildKey) ? androidPlugin[nativeBuildKey] : true @@ -66,18 +68,28 @@ class NativePluginLoader { // "path": "/path/to/plugin-a", // "dependencies": ["plugin-b", "plugin-c"], // "native_build": true + // "dev_dependency": false // }, // { // "name": "plugin-b", // "path": "/path/to/plugin-b", // "dependencies": ["plugin-c"], // "native_build": true + // "dev_dependency": false // }, // { // "name": "plugin-c", // "path": "/path/to/plugin-c", // "dependencies": [], // "native_build": true + // "dev_dependency": false + // }, + // { + // "name": "plugin-d", + // "path": "/path/to/plugin-d", + // "dependencies": [], + // "native_build": true + // "dev_dependency": true // }, // ], // }, @@ -93,12 +105,18 @@ class NativePluginLoader { // { // "name": "plugin-c", // "dependencies": [] + // }, + // { + // "name": "plugin-d", + // "dependencies": [] // } // ] // } // This means, `plugin-a` depends on `plugin-b` and `plugin-c`. // `plugin-b` depends on `plugin-c`. // `plugin-c` doesn't depend on anything. + // `plugin-d` also doesn't depend on anything, but it is a dev + // dependency to the Flutter project, so it is marked as such. if (parsedFlutterPluginsDependencies) { return parsedFlutterPluginsDependencies } diff --git a/packages/flutter_tools/gradle/src/main/kotlin/dependency_version_checker.gradle.kts b/packages/flutter_tools/gradle/src/main/kotlin/dependency_version_checker.gradle.kts index 834038ae85f..d785fb43b59 100644 --- a/packages/flutter_tools/gradle/src/main/kotlin/dependency_version_checker.gradle.kts +++ b/packages/flutter_tools/gradle/src/main/kotlin/dependency_version_checker.gradle.kts @@ -88,16 +88,16 @@ class DependencyVersionChecker { // Before updating any "error" version, ensure that you have updated the corresponding // "warn" version for a full release to provide advanced warning. See // flutter.dev/go/android-dependency-versions for more. - val warnGradleVersion: Version = Version(7, 1, 0) + val warnGradleVersion: Version = Version(7, 4, 2) val errorGradleVersion: Version = Version(7, 0, 2) val warnJavaVersion: JavaVersion = JavaVersion.VERSION_11 val errorJavaVersion: JavaVersion = JavaVersion.VERSION_1_1 - val warnAGPVersion: Version = Version(7, 0, 1) + val warnAGPVersion: Version = Version(7, 3, 1) val errorAGPVersion: Version = Version(7, 0, 0) - val warnKGPVersion: Version = Version(1, 7, 10) + val warnKGPVersion: Version = Version(1, 8, 10) val errorKGPVersion: Version = Version(1, 7, 0) /** diff --git a/packages/flutter_tools/lib/executable.dart b/packages/flutter_tools/lib/executable.dart index 1ebf5c1ee82..ce0a5a66a17 100644 --- a/packages/flutter_tools/lib/executable.dart +++ b/packages/flutter_tools/lib/executable.dart @@ -43,13 +43,13 @@ import 'src/commands/symbolize.dart'; import 'src/commands/test.dart'; import 'src/commands/update_packages.dart'; import 'src/commands/upgrade.dart'; +import 'src/commands/widget_preview.dart'; import 'src/devtools_launcher.dart'; import 'src/features.dart'; import 'src/globals.dart' as globals; // Files in `isolated` are intentionally excluded from google3 tooling. import 'src/isolated/build_targets.dart'; import 'src/isolated/mustache_template.dart'; -import 'src/isolated/native_assets/native_assets.dart'; import 'src/isolated/native_assets/test/native_assets.dart'; import 'src/isolated/resident_web_runner.dart'; import 'src/native_assets.dart'; @@ -181,7 +181,6 @@ List generateCommands({ platform: globals.platform, processInfo: globals.processInfo, fileSystem: globals.fs, - nativeAssetsBuilder: const HotRunnerNativeAssetsBuilderImpl(), ), BuildCommand( artifacts: globals.artifacts!, @@ -244,7 +243,6 @@ List generateCommands({ ), RunCommand( verboseHelp: verboseHelp, - nativeAssetsBuilder: const HotRunnerNativeAssetsBuilderImpl(), ), ScreenshotCommand(fs: globals.fs), ShellCompletionCommand(), @@ -253,6 +251,7 @@ List generateCommands({ verbose: verbose, nativeAssetsBuilder: globals.nativeAssetsBuilder, ), + WidgetPreviewCommand(), UpgradeCommand(verboseHelp: verboseHelp), SymbolizeCommand( stdio: globals.stdio, diff --git a/packages/flutter_tools/lib/runner.dart b/packages/flutter_tools/lib/runner.dart index f1a46f9a9aa..f9a43623874 100644 --- a/packages/flutter_tools/lib/runner.dart +++ b/packages/flutter_tools/lib/runner.dart @@ -73,47 +73,28 @@ Future run( exitCode: 1); } - // Disable analytics if user passes in the `--disable-analytics` option - // "flutter --disable-analytics" - // - // Same functionality as "flutter config --no-analytics" for disabling - // except with the `value` hard coded as false if (args.contains('--disable-analytics')) { - // The tool sends the analytics event *before* toggling the flag - // intentionally to be sure that opt-out events are sent correctly. - AnalyticsConfigEvent(enabled: false).send(); - - // Normally, the tool waits for the analytics to all send before the - // tool exits, but only when analytics are enabled. When reporting that - // analytics have been disable, the wait must be done here instead. - await globals.flutterUsage.ensureAnalyticsSent(); - - globals.flutterUsage.enabled = false; - globals.printStatus('Analytics reporting disabled.'); - - // TODO(eliasyishak): Set the telemetry for the unified_analytics - // package as well, the above will be removed once we have - // fully transitioned to using the new package, https://github.com/flutter/flutter/issues/128251 + if (globals.analytics.telemetryEnabled) { + globals.analytics.send( + Event.analyticsCollectionEnabled(status: false), + ); + // Before disablig analytics, we need to close the client to make + // sure the above collection event is sent. + await globals.analytics.close(); + } await globals.analytics.setTelemetry(false); + globals.printStatus('Analytics reporting disabled.'); } - // Enable analytics if user passes in the `--enable-analytics` option - // `flutter --enable-analytics` - // - // Same functionality as `flutter config --analytics` for enabling - // except with the `value` hard coded as true if (args.contains('--enable-analytics')) { - // The tool sends the analytics event *before* toggling the flag - // intentionally to be sure that opt-out events are sent correctly. - AnalyticsConfigEvent(enabled: true).send(); - - globals.flutterUsage.enabled = true; - globals.printStatus('Analytics reporting enabled.'); - - // TODO(eliasyishak): Set the telemetry for the unified_analytics - // package as well, the above will be removed once we have - // fully transitioned to using the new package, https://github.com/flutter/flutter/issues/128251 + final bool alreadyEnabled = globals.analytics.telemetryEnabled; await globals.analytics.setTelemetry(true); + if (!alreadyEnabled) { + globals.analytics.send( + Event.analyticsCollectionEnabled(status: true), + ); + } + globals.printStatus('Analytics reporting enabled.'); } // Send an event to GA3 for any users that are opted into GA3 diff --git a/packages/flutter_tools/lib/src/android/android_device.dart b/packages/flutter_tools/lib/src/android/android_device.dart index 40a291ae0b3..90d2ebdab7f 100644 --- a/packages/flutter_tools/lib/src/android/android_device.dart +++ b/packages/flutter_tools/lib/src/android/android_device.dart @@ -6,6 +6,7 @@ import 'dart:async'; import 'package:meta/meta.dart'; import 'package:process/process.dart'; +import 'package:vm_service/vm_service.dart'; import '../application_package.dart'; import '../base/common.dart' show throwToolExit; @@ -21,6 +22,7 @@ import '../device_port_forwarder.dart'; import '../device_vm_service_discovery_for_attach.dart'; import '../project.dart'; import '../protocol_discovery.dart'; +import '../vmservice.dart'; import 'android.dart'; import 'android_builder.dart'; import 'android_console.dart'; @@ -618,6 +620,7 @@ class AndroidDevice extends Device { await AdbLogReader.createLogReader( this, _processManager, + _logger, ), portForwarder: portForwarder, hostPort: debuggingOptions.hostVmServicePort, @@ -796,12 +799,14 @@ class AndroidDevice extends Device { return _pastLogReader ??= await AdbLogReader.createLogReader( this, _processManager, + _logger, includePastLogs: true, ); } else { return _logReader ??= await AdbLogReader.createLogReader( this, _processManager, + _logger, ); } } @@ -1042,15 +1047,20 @@ class AndroidMemoryInfo extends MemoryInfo { /// A log reader that logs from `adb logcat`. class AdbLogReader extends DeviceLogReader { - AdbLogReader._(this._adbProcess, this.name); + AdbLogReader._(this._adbProcess, this.name, this._logger); @visibleForTesting - factory AdbLogReader.test(Process adbProcess, String name) = AdbLogReader._; + factory AdbLogReader.test( + Process adbProcess, + String name, + Logger logger, + ) = AdbLogReader._; /// Create a new [AdbLogReader] from an [AndroidDevice] instance. static Future createLogReader( AndroidDevice device, - ProcessManager processManager, { + ProcessManager processManager, + Logger logger, { bool includePastLogs = false, }) async { // logcat -T is not supported on Android releases before Lollipop. @@ -1085,11 +1095,15 @@ class AdbLogReader extends DeviceLogReader { ]); } final Process process = await processManager.start(device.adbCommandForDevice(args)); - return AdbLogReader._(process, device.name); + return AdbLogReader._(process, device.name, logger); } + int? _appPid; + final Process _adbProcess; + final Logger _logger; + @override final String name; @@ -1101,6 +1115,17 @@ class AdbLogReader extends DeviceLogReader { @override Stream get logLines => _linesController.stream; + @override + Future provideVmService(FlutterVmService connectedVmService) async { + final VM? vm = await connectedVmService.getVmGuarded(); + if (vm == null) { + _logger.printError('An error occurred when setting up filtering for adb logs. ' + 'Unable to communicate with the VM service.'); + } else { + _appPid = vm.pid; + } + } + void _start() { // We expect logcat streams to occasionally contain invalid utf-8, // see: https://github.com/flutter/flutter/pull/8864. @@ -1189,7 +1214,7 @@ class AdbLogReader extends DeviceLogReader { _fatalCrash = false; } } - } else if (appPid != null && int.parse(logMatch.group(1)!) == appPid) { + } else if (_appPid != null && int.parse(logMatch.group(1)!) == _appPid) { acceptLine = !_surfaceSyncerSpam.hasMatch(line); if (_fatalLog.hasMatch(line)) { diff --git a/packages/flutter_tools/lib/src/android/android_workflow.dart b/packages/flutter_tools/lib/src/android/android_workflow.dart index 838638c1512..2f9e434bfd1 100644 --- a/packages/flutter_tools/lib/src/android/android_workflow.dart +++ b/packages/flutter_tools/lib/src/android/android_workflow.dart @@ -105,7 +105,12 @@ class AndroidValidator extends DoctorValidator { messages.add(ValidationMessage.error(_userMessages.androidMissingJdk)); return false; } - messages.add(ValidationMessage(_userMessages.androidJdkLocation(_java!.binaryPath))); + messages.add(ValidationMessage( + _androidJdkLocationMessage( + _java!.binaryPath, + _java.javaSource, + ), + )); if (!_java.canRun()) { messages.add(ValidationMessage.error(_userMessages.androidCantRunJavaBinary(_java.binaryPath))); return false; @@ -454,3 +459,26 @@ class AndroidLicenseValidator extends DoctorValidator { ); } } + +String _androidJdkLocationMessage(String location, JavaSource source) { + final String setWithConfigBreadcrumb = switch (source) { + JavaSource.androidStudio || JavaSource.path || JavaSource.javaHome => + 'To manually set the JDK path, use: `flutter config --jdk-dir="path/to/jdk"`.', + JavaSource.flutterConfig => + 'To change the current JDK, run: `flutter config --jdk-dir="path/to/jdk"`.' + }; + final String sourceMessagePart = switch (source) { + JavaSource.androidStudio => + 'This is the JDK bundled with the latest Android Studio installation on this machine.', + JavaSource.javaHome => + 'This JDK is specified by the JAVA_HOME environment variable.', + JavaSource.path => + 'This JDK was found in the system PATH.', + JavaSource.flutterConfig => + 'This JDK is specified in your Flutter configuration.', + }; + + return 'Java binary at: $location\n' + '$sourceMessagePart\n' + '$setWithConfigBreadcrumb'; +} diff --git a/packages/flutter_tools/lib/src/android/gradle.dart b/packages/flutter_tools/lib/src/android/gradle.dart index eb647f27ac0..f2cc1e95f82 100644 --- a/packages/flutter_tools/lib/src/android/gradle.dart +++ b/packages/flutter_tools/lib/src/android/gradle.dart @@ -122,6 +122,11 @@ String getAarTaskFor(BuildInfo buildInfo) { return _taskFor('assembleAar', buildInfo); } +@visibleForTesting +const String androidX86DeprecationWarning = + 'Support for Android x86 targets will be removed in the next stable release after 3.27. ' + 'See https://github.com/flutter/flutter/issues/157543 for details.'; + /// Returns the output APK file names for a given [AndroidBuildInfo]. /// /// For example, when [splitPerAbi] is true, multiple APKs are created. @@ -188,6 +193,13 @@ class AndroidGradleBuilder implements AndroidBuilder { // Module projects artifacts are located in `build/host`. outputDirectory = outputDirectory.childDirectory('host'); } + + final bool containsX86Targets = androidBuildInfo.where( + (AndroidBuildInfo info) => info.containsX86Target, + ).isNotEmpty; + if (containsX86Targets) { + _logger.printWarning(androidX86DeprecationWarning); + } for (final AndroidBuildInfo androidBuildInfo in androidBuildInfo) { await buildGradleAar( project: project, @@ -300,6 +312,9 @@ class AndroidGradleBuilder implements AndroidBuilder { int retry = 0, @visibleForTesting int? maxRetries, }) async { + if (androidBuildInfo.containsX86Target) { + _logger.printWarning(androidX86DeprecationWarning); + } if (!project.android.isSupportedVersion) { _exitWithUnsupportedProjectMessage(_logger.terminal, _analytics); } @@ -629,14 +644,9 @@ class AndroidGradleBuilder implements AndroidBuilder { 'A summary of your ${kind.toUpperCase()} analysis can be found at: ${outputFile.path}', ); - // DevTools expects a file path relative to the .flutter-devtools/ dir. - final String relativeAppSizePath = outputFile.path - .split('.flutter-devtools/') - .last - .trim(); _logger.printStatus( '\nTo analyze your app size in Dart DevTools, run the following command:\n' - 'dart devtools --appSizeBase=$relativeAppSizePath' + 'dart devtools --appSizeBase=${outputFile.path}' ); } diff --git a/packages/flutter_tools/lib/src/android/gradle_errors.dart b/packages/flutter_tools/lib/src/android/gradle_errors.dart index fa451177754..4402339975e 100644 --- a/packages/flutter_tools/lib/src/android/gradle_errors.dart +++ b/packages/flutter_tools/lib/src/android/gradle_errors.dart @@ -511,7 +511,7 @@ final RegExp _agpJavaError = RegExp(r'Android Gradle plugin requires Java (\d+\. // Android Gradle Plugin handles the error here: http://shortn/_SgUWyRdywL. // If we ever need to reference or check the thrown requirements, -// we can find the Java and Android Gradle Plugin compatability here: +// we can find the Java and Android Gradle Plugin compatibility here: // 'https://developer.android.com/build/releases/past-releases' @visibleForTesting final GradleHandledError incompatibleJavaAndAgpVersionsHandler= GradleHandledError( diff --git a/packages/flutter_tools/lib/src/android/java.dart b/packages/flutter_tools/lib/src/android/java.dart index 44d3f83647c..c7252b01ca0 100644 --- a/packages/flutter_tools/lib/src/android/java.dart +++ b/packages/flutter_tools/lib/src/android/java.dart @@ -15,11 +15,25 @@ import 'android_studio.dart'; const String _javaExecutable = 'java'; +enum JavaSource { + /// JDK bundled with latest Android Studio installation. + androidStudio, + /// JDK specified by the system's JAVA_HOME environment variable. + javaHome, + /// JDK available through the system's PATH environment variable. + path, + /// JDK specified in Flutter's configuration. + flutterConfig, +} + +typedef _JavaHomePathWithSource = ({String path, JavaSource source}); + /// Represents an installation of Java. class Java { Java({ required this.javaHome, required this.binaryPath, + required this.javaSource, required Logger logger, required FileSystem fileSystem, required OperatingSystemUtils os, @@ -65,7 +79,7 @@ class Java { platform: platform, processManager: processManager ); - final String? home = _findJavaHome( + final _JavaHomePathWithSource? home = _findJavaHome( config: config, logger: logger, androidStudio: androidStudio, @@ -73,7 +87,7 @@ class Java { ); final String? binary = _findJavaBinary( logger: logger, - javaHome: home, + javaHome: home?.path, fileSystem: fileSystem, operatingSystemUtils: os, platform: platform @@ -83,9 +97,14 @@ class Java { return null; } + // If javaHome == null and binary is not null, it means that + // binary obtained from PATH as fallback. + final JavaSource javaSource = home?.source ?? JavaSource.path; + return Java( - javaHome: home, + javaHome: home?.path, binaryPath: binary, + javaSource: javaSource, logger: logger, fileSystem: fileSystem, os: os, @@ -110,6 +129,12 @@ class Java { /// to this class instead. final String binaryPath; + /// Indicates the source from where the Java runtime was located. + /// + /// This information is useful for debugging and logging purposes to track + /// which source was used to locate the Java runtime environment. + final JavaSource javaSource; + final Logger _logger; final FileSystem _fileSystem; final OperatingSystemUtils _os; @@ -192,7 +217,7 @@ class Java { } } -String? _findJavaHome({ +_JavaHomePathWithSource? _findJavaHome({ required Config config, required Logger logger, required AndroidStudio? androidStudio, @@ -200,17 +225,17 @@ String? _findJavaHome({ }) { final Object? configured = config.getValue('jdk-dir'); if (configured != null) { - return configured as String; + return (path: configured as String, source: JavaSource.flutterConfig); } final String? androidStudioJavaPath = androidStudio?.javaPath; if (androidStudioJavaPath != null) { - return androidStudioJavaPath; + return (path: androidStudioJavaPath, source: JavaSource.androidStudio); } final String? javaHomeEnv = platform.environment[Java.javaHomeEnvironmentVariable]; if (javaHomeEnv != null) { - return javaHomeEnv; + return (path: javaHomeEnv, source: JavaSource.javaHome); } return null; } diff --git a/packages/flutter_tools/lib/src/base/dds.dart b/packages/flutter_tools/lib/src/base/dds.dart index 6a5ece2c29d..39cdd671619 100644 --- a/packages/flutter_tools/lib/src/base/dds.dart +++ b/packages/flutter_tools/lib/src/base/dds.dart @@ -96,22 +96,11 @@ class DartDevelopmentService with DartDevelopmentServiceLocalOperationsMixin { Artifact.engineDartBinary, ), ); - - // Complete the future if the DDS process is null, which happens in - // testing. unawaited(_ddsInstance!.done.whenComplete(completeFuture)); } on DartDevelopmentServiceException catch (e) { _logger.printTrace('Warning: Failed to start DDS: ${e.message}'); if (e is ExistingDartDevelopmentServiceException) { _existingDdsUri = e.ddsUri; - } else { - _logger.printError( - 'DDS has failed to start and there is not an existing DDS instance ' - 'available to connect to. Please file an issue at https://github.com/flutter/flutter/issues ' - 'with the following error message:\n\n ${e.message}.'); - // DDS was unable to start for an unknown reason. Raise a StateError - // so it can be reported by the crash reporter. - throw StateError(e.message); } completeFuture(); rethrow; diff --git a/packages/flutter_tools/lib/src/base/deferred_component.dart b/packages/flutter_tools/lib/src/base/deferred_component.dart index 0c6f675a91e..fe7438b6d0b 100644 --- a/packages/flutter_tools/lib/src/base/deferred_component.dart +++ b/packages/flutter_tools/lib/src/base/deferred_component.dart @@ -78,6 +78,20 @@ class DeferredComponent { }; } + /// Returns a descriptor of the component to be used when modifying a + /// pubspec.yaml. + Map get descriptor { + return { + 'name': name, + if (libraries.isNotEmpty) + 'libraries': libraries.toList(), + if (assets.isNotEmpty) + 'assets': assets.map( + (AssetsEntry e) => e.descriptor, + ).toList(), + }; + } + /// Provides a human readable string representation of the /// configuration. @override diff --git a/packages/flutter_tools/lib/src/base/error_handling_io.dart b/packages/flutter_tools/lib/src/base/error_handling_io.dart index 41bc27e8859..0dd57ef55bc 100644 --- a/packages/flutter_tools/lib/src/base/error_handling_io.dart +++ b/packages/flutter_tools/lib/src/base/error_handling_io.dart @@ -7,7 +7,6 @@ import 'dart:io' as io show Directory, File, Link, Process, ProcessException, Pr import 'dart:typed_data'; import 'package:file/file.dart'; -import 'package:meta/meta.dart'; import 'package:path/path.dart' as p; // flutter_ignore: package_path_import import 'package:process/process.dart'; @@ -47,7 +46,6 @@ class ErrorHandlingFileSystem extends ForwardingFileSystem { _platform = platform, super(delegate); - @visibleForTesting FileSystem get fileSystem => delegate; final Platform _platform; @@ -124,7 +122,7 @@ class ErrorHandlingFileSystem extends ForwardingFileSystem { @override Directory get systemTempDirectory { - return directory(delegate.systemTempDirectory); + return _runSync(() => directory(delegate.systemTempDirectory), platform: _platform); } @override diff --git a/packages/flutter_tools/lib/src/base/file_system.dart b/packages/flutter_tools/lib/src/base/file_system.dart index be4cf52a203..e0e66818160 100644 --- a/packages/flutter_tools/lib/src/base/file_system.dart +++ b/packages/flutter_tools/lib/src/base/file_system.dart @@ -198,6 +198,11 @@ class LocalFileSystem extends local_fs.LocalFileSystem { final ShutdownHooks shutdownHooks; + // Indicates that `dispose()` has been invoked or some shutdown hook has executed, + // resulting in the underlying temporary directory being cleaned up. + bool get disposed => _disposed; + bool _disposed = false; + Future dispose() async { _tryToDeleteTemp(); for (final MapEntry signalToken in _signalTokens.entries) { @@ -210,6 +215,7 @@ class LocalFileSystem extends local_fs.LocalFileSystem { final List _fatalSignals; void _tryToDeleteTemp() { + _disposed = true; try { if (_systemTemp?.existsSync() ?? false) { _systemTemp?.deleteSync(recursive: true); diff --git a/packages/flutter_tools/lib/src/base/logger.dart b/packages/flutter_tools/lib/src/base/logger.dart index b6d185d067f..d53b58713d2 100644 --- a/packages/flutter_tools/lib/src/base/logger.dart +++ b/packages/flutter_tools/lib/src/base/logger.dart @@ -1145,27 +1145,26 @@ typedef SlowWarningCallback = String Function(); /// a [Status] or one of its subclasses. abstract class Status { Status({ - this.onFinish, + VoidCallback? onFinish, required Stopwatch stopwatch, - this.timeout, - }) : _stopwatch = stopwatch; + Duration? timeout, + }) : _timeout = timeout, + _onFinish = onFinish, + _stopwatch = stopwatch; - final VoidCallback? onFinish; - final Duration? timeout; + final VoidCallback? _onFinish; + final Duration? _timeout; - @protected final Stopwatch _stopwatch; - @protected - String get elapsedTime { + String get _elapsedTime { if (_stopwatch.elapsed.inSeconds > 2) { return getElapsedAsSeconds(_stopwatch.elapsed); } return getElapsedAsMilliseconds(_stopwatch.elapsed); } - @visibleForTesting - bool get seemsSlow => timeout != null && _stopwatch.elapsed > timeout!; + bool get seemsSlow => _timeout != null && _stopwatch.elapsed > _timeout; /// Call to start spinning. void start() { @@ -1193,7 +1192,7 @@ abstract class Status { void finish() { assert(_stopwatch.isRunning); _stopwatch.stop(); - onFinish?.call(); + _onFinish?.call(); } } @@ -1206,7 +1205,7 @@ class SilentStatus extends Status { @override void finish() { - onFinish?.call(); + _onFinish?.call(); } } @@ -1216,15 +1215,17 @@ const int _kTimePadding = 8; // should fit "99,999ms" /// [onFinish]. On [stop], will additionally print out summary information. class SummaryStatus extends Status { SummaryStatus({ - this.message = '', + String message = '', required super.stopwatch, - this.padding = kDefaultStatusPadding, + int padding = kDefaultStatusPadding, super.onFinish, required Stdio stdio, - }) : _stdio = stdio; + }) : _padding = padding, + _message = message, + _stdio = stdio; - final String message; - final int padding; + final String _message; + final int _padding; final Stdio _stdio; bool _messageShowingOnCurrentLine = false; @@ -1239,7 +1240,7 @@ class SummaryStatus extends Status { void _printMessage() { assert(!_messageShowingOnCurrentLine); - _writeToStdOut('${message.padRight(padding)} '); + _writeToStdOut('${_message.padRight(_padding)} '); _messageShowingOnCurrentLine = true; } @@ -1250,7 +1251,7 @@ class SummaryStatus extends Status { } super.stop(); assert(_messageShowingOnCurrentLine); - _writeToStdOut(elapsedTime.padLeft(_kTimePadding)); + _writeToStdOut(_elapsedTime.padLeft(_kTimePadding)); _writeToStdOut('\n'); } @@ -1281,18 +1282,20 @@ class AnonymousSpinnerStatus extends Status { required super.stopwatch, required Stdio stdio, required Terminal terminal, - this.slowWarningCallback, - this.warningColor, + SlowWarningCallback? slowWarningCallback, + TerminalColor? warningColor, super.timeout, - }) : _stdio = stdio, - _terminal = terminal, - _animation = _selectAnimation(terminal); + }) : _warningColor = warningColor, + _slowWarningCallback = slowWarningCallback, + _stdio = stdio, + _terminal = terminal, + _animation = _selectAnimation(terminal); final Stdio _stdio; final Terminal _terminal; String _slowWarning = ''; - final SlowWarningCallback? slowWarningCallback; - final TerminalColor? warningColor; + final SlowWarningCallback? _slowWarningCallback; + final TerminalColor? _warningColor; static const String _backspaceChar = '\b'; static const String _clearChar = ' '; @@ -1333,10 +1336,14 @@ class AnonymousSpinnerStatus extends Status { final List _animation; - Timer? timer; - int ticks = 0; + Timer? _timer; + + int _ticks = 0; + @visibleForTesting + int get ticks => _ticks; + int _lastAnimationFrameLength = 0; - bool timedOut = false; + bool _timedOut = false; String get _currentAnimationFrame => _animation[ticks % _animation.length]; int get _currentLineLength => _lastAnimationFrameLength + _slowWarning.length; @@ -1354,30 +1361,30 @@ class AnonymousSpinnerStatus extends Status { @override void start() { super.start(); - assert(timer == null); + assert(_timer == null); _startSpinner(); } void _startSpinner() { - timer = Timer.periodic(const Duration(milliseconds: 100), _callback); - _callback(timer!); + _timer = Timer.periodic(const Duration(milliseconds: 100), _callback); + _callback(_timer!); } void _callback(Timer timer) { - assert(this.timer == timer); + assert(_timer == timer); assert(timer.isActive); _writeToStdOut(_backspaceChar * _lastAnimationFrameLength); - ticks += 1; + _ticks += 1; if (seemsSlow) { - if (!timedOut) { - timedOut = true; + if (!_timedOut) { + _timedOut = true; if (_currentLineLength > _lastAnimationFrameLength) { _clear(_currentLineLength - _lastAnimationFrameLength); } } - final SlowWarningCallback? callback = slowWarningCallback; + final SlowWarningCallback? callback = _slowWarningCallback; if (_slowWarning.isEmpty && callback != null) { - final TerminalColor? color = warningColor; + final TerminalColor? color = _warningColor; if (color != null) { _slowWarning = _terminal.color(callback(), color); } else { @@ -1394,30 +1401,30 @@ class AnonymousSpinnerStatus extends Status { @override void pause() { - assert(timer != null); - assert(timer!.isActive); + assert(_timer != null); + assert(_timer!.isActive); if (_terminal.supportsColor) { _writeToStdOut('\r\x1B[K'); // go to start of line and clear line } else { _clear(_currentLineLength); } _lastAnimationFrameLength = 0; - timer?.cancel(); + _timer?.cancel(); } @override void resume() { - assert(timer != null); - assert(!timer!.isActive); + assert(_timer != null); + assert(!_timer!.isActive); _startSpinner(); } @override void finish() { - assert(timer != null); - assert(timer!.isActive); - timer?.cancel(); - timer = null; + assert(_timer != null); + assert(_timer!.isActive); + _timer?.cancel(); + _timer = null; _clear(_lastAnimationFrameLength + _slowWarning.length); _slowWarning = ''; _lastAnimationFrameLength = 0; @@ -1436,16 +1443,17 @@ class AnonymousSpinnerStatus extends Status { /// Call [pause] before outputting any text while this is running. class SpinnerStatus extends AnonymousSpinnerStatus { SpinnerStatus({ - required this.message, - this.padding = kDefaultStatusPadding, + required String message, + int padding = kDefaultStatusPadding, super.onFinish, required super.stopwatch, required super.stdio, required super.terminal, - }); + }) : _padding = padding, + _message = message; - final String message; - final int padding; + final String _message; + final int _padding; static final String _margin = AnonymousSpinnerStatus._clearChar * (5 + _kTimePadding - 1); @@ -1461,7 +1469,7 @@ class SpinnerStatus extends AnonymousSpinnerStatus { } void _printStatus() { - final String line = '${message.padRight(padding)}$_margin'; + final String line = '${_message.padRight(_padding)}$_margin'; _totalMessageLength = line.length; _writeToStdOut(line); } @@ -1483,7 +1491,7 @@ class SpinnerStatus extends AnonymousSpinnerStatus { super.stop(); // calls finish, which clears the spinner assert(_totalMessageLength > _kTimePadding); _writeToStdOut(AnonymousSpinnerStatus._backspaceChar * (_kTimePadding - 1)); - _writeToStdOut(elapsedTime.padLeft(_kTimePadding)); + _writeToStdOut(_elapsedTime.padLeft(_kTimePadding)); _writeToStdOut('\n'); } diff --git a/packages/flutter_tools/lib/src/base/user_messages.dart b/packages/flutter_tools/lib/src/base/user_messages.dart index 7bafeb8e7f7..c260616539e 100644 --- a/packages/flutter_tools/lib/src/base/user_messages.dart +++ b/packages/flutter_tools/lib/src/base/user_messages.dart @@ -115,7 +115,6 @@ class UserMessages { 'No Java Development Kit (JDK) found; You must have the environment ' 'variable JAVA_HOME set and the java binary in your PATH. ' 'You can download the JDK from https://www.oracle.com/technetwork/java/javase/downloads/.'; - String androidJdkLocation(String location) => 'Java binary at: $location'; String get androidLicensesAll => 'All Android licenses accepted.'; String get androidLicensesSome => 'Some Android licenses not accepted. To resolve this, run: flutter doctor --android-licenses'; String get androidLicensesNone => 'Android licenses not accepted. To resolve this, run: flutter doctor --android-licenses'; diff --git a/packages/flutter_tools/lib/src/build_info.dart b/packages/flutter_tools/lib/src/build_info.dart index 50e076beaa0..842a6373d95 100644 --- a/packages/flutter_tools/lib/src/build_info.dart +++ b/packages/flutter_tools/lib/src/build_info.dart @@ -396,6 +396,8 @@ class AndroidBuildInfo { /// The target platforms for the build. final Iterable targetArchs; + bool get containsX86Target => targetArchs.contains(AndroidArch.x86); + /// Whether to bootstrap an empty application. final bool fastStart; } diff --git a/packages/flutter_tools/lib/src/build_system/build_system.dart b/packages/flutter_tools/lib/src/build_system/build_system.dart index 6a4eac673ce..83631b2afeb 100644 --- a/packages/flutter_tools/lib/src/build_system/build_system.dart +++ b/packages/flutter_tools/lib/src/build_system/build_system.dart @@ -347,7 +347,6 @@ class Environment { required Analytics analytics, String? engineVersion, required bool generateDartPluginRegistry, - required bool useImplicitPubspecResolution, Directory? buildDir, Map defines = const {}, Map inputs = const {}, @@ -392,7 +391,6 @@ class Environment { engineVersion: engineVersion, inputs: inputs, generateDartPluginRegistry: generateDartPluginRegistry, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); } @@ -414,7 +412,6 @@ class Environment { Usage? usage, Analytics? analytics, bool generateDartPluginRegistry = false, - bool useImplicitPubspecResolution = true, required FileSystem fileSystem, required Logger logger, required Artifacts artifacts, @@ -438,7 +435,6 @@ class Environment { analytics: analytics ?? const NoOpAnalytics(), engineVersion: engineVersion, generateDartPluginRegistry: generateDartPluginRegistry, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); } @@ -461,7 +457,6 @@ class Environment { this.engineVersion, required this.inputs, required this.generateDartPluginRegistry, - required this.useImplicitPubspecResolution, }); /// The [Source] value which is substituted with the path to [projectDir]. @@ -493,7 +488,7 @@ class Environment { /// The path to the package configuration file to use for compilation. /// /// This is used by package:package_config to locate the actual package_config.json - /// file. If not provided, defaults to `.dart_tool/package_config.json`. + /// file. If not provided in tests, defaults to `.dart_tool/package_config.json`. final String packageConfigPath; /// The `BUILD_DIR` environment variable. @@ -562,10 +557,6 @@ class Environment { /// the new entrypoint. final bool generateDartPluginRegistry; - /// Whether to generate a `.flutter-plugins` file and for Flutter i10n source - /// generation to default to `synthetic-package: true`. - final bool useImplicitPubspecResolution; - late final DepfileService depFileService = DepfileService( logger: logger, fileSystem: fileSystem, diff --git a/packages/flutter_tools/lib/src/build_system/targets/android.dart b/packages/flutter_tools/lib/src/build_system/targets/android.dart index d1b7dc62a30..569b5b6576f 100644 --- a/packages/flutter_tools/lib/src/build_system/targets/android.dart +++ b/packages/flutter_tools/lib/src/build_system/targets/android.dart @@ -7,6 +7,7 @@ import '../../base/build.dart'; import '../../base/deferred_component.dart'; import '../../base/file_system.dart'; import '../../build_info.dart'; +import '../../devfs.dart'; import '../../globals.dart' as globals show xcode; import '../../project.dart'; import '../build_system.dart'; @@ -15,6 +16,7 @@ import '../exceptions.dart'; import 'assets.dart'; import 'common.dart'; import 'icon_tree_shaker.dart'; +import 'native_assets.dart'; /// Prepares the asset bundle in the format expected by flutter.gradle. /// @@ -68,6 +70,10 @@ abstract class AndroidAssetBundle extends Target { targetPlatform: TargetPlatform.android, buildMode: buildMode, flavor: environment.defines[kFlavor], + additionalContent: { + 'NativeAssetsManifest.json': + DevFSFileContent(environment.buildDir.childFile('native_assets.json')), + }, ); environment.depFileService.writeToFile( assetDepfile, @@ -78,6 +84,7 @@ abstract class AndroidAssetBundle extends Target { @override List get dependencies => const [ KernelSnapshot(), + InstallCodeAssets(), ]; } diff --git a/packages/flutter_tools/lib/src/build_system/targets/assets.dart b/packages/flutter_tools/lib/src/build_system/targets/assets.dart index ce10d1222df..14cbe0890b9 100644 --- a/packages/flutter_tools/lib/src/build_system/targets/assets.dart +++ b/packages/flutter_tools/lib/src/build_system/targets/assets.dart @@ -22,6 +22,7 @@ import '../tools/scene_importer.dart'; import '../tools/shader_compiler.dart'; import 'common.dart'; import 'icon_tree_shaker.dart'; +import 'native_assets.dart'; /// A helper function to copy an asset bundle into an [environment]'s output /// directory. @@ -329,6 +330,7 @@ class CopyAssets extends Target { @override List get dependencies => const [ KernelSnapshot(), + InstallCodeAssets(), ]; @override @@ -363,6 +365,10 @@ class CopyAssets extends Target { targetPlatform: TargetPlatform.android, buildMode: buildMode, flavor: environment.defines[kFlavor], + additionalContent: { + 'NativeAssetsManifest.json': + DevFSFileContent(environment.buildDir.childFile('native_assets.json')), + }, ); environment.depFileService.writeToFile( depfile, diff --git a/packages/flutter_tools/lib/src/build_system/targets/common.dart b/packages/flutter_tools/lib/src/build_system/targets/common.dart index 179b46a2026..a1b40952293 100644 --- a/packages/flutter_tools/lib/src/build_system/targets/common.dart +++ b/packages/flutter_tools/lib/src/build_system/targets/common.dart @@ -3,16 +3,15 @@ // found in the LICENSE file. import 'package:package_config/package_config.dart'; -import 'package:yaml/yaml.dart'; import '../../artifacts.dart'; import '../../base/build.dart'; -import '../../base/common.dart'; import '../../base/file_system.dart'; import '../../base/io.dart'; import '../../build_info.dart'; import '../../compile.dart'; import '../../dart/package_map.dart'; +import '../../devfs.dart'; import '../../globals.dart' as globals show xcode; import '../build_system.dart'; import '../depfile.dart'; @@ -81,6 +80,10 @@ class CopyFlutterBundle extends Target { targetPlatform: TargetPlatform.android, buildMode: buildMode, flavor: flavor, + additionalContent: { + 'NativeAssetsManifest.json': + DevFSFileContent(environment.buildDir.childFile('native_assets.json')), + }, ); environment.depFileService.writeToFile( assetDepfile, @@ -91,6 +94,7 @@ class CopyFlutterBundle extends Target { @override List get dependencies => const [ KernelSnapshot(), + InstallCodeAssets(), ]; } @@ -122,11 +126,8 @@ class ReleaseCopyFlutterBundle extends CopyFlutterBundle { /// even though it is not listed as an input. Pub inserts a timestamp into /// the file which causes unnecessary rebuilds, so instead a subset of the contents /// are used an input instead. -/// -/// This kernel snapshot is concatenated with the [KernelSnapshotNativeAssets] -/// inside [KernelSnapshot] byte-wise to create the combined kernel snapshot. -class KernelSnapshotProgram extends Target { - const KernelSnapshotProgram(); +class KernelSnapshot extends Target { + const KernelSnapshot(); @override String get name => 'kernel_snapshot_program'; @@ -143,7 +144,7 @@ class KernelSnapshotProgram extends Target { @override List get outputs => const [ - Source.pattern('{BUILD_DIR}/${KernelSnapshotProgram.dillName}'), + Source.pattern('{BUILD_DIR}/${KernelSnapshot.dillName}'), // TODO(mosuem): Should output resources.json. https://github.com/flutter/flutter/issues/146263 ]; @@ -160,7 +161,7 @@ class KernelSnapshotProgram extends Target { DartPluginRegistrantTarget(), ]; - static const String dillName = 'program.dill'; + static const String dillName = 'app.dill'; @override Future build(Environment environment) async { @@ -276,150 +277,6 @@ class KernelSnapshotProgram extends Target { } } -/// Generate a kernel snapshot of the native assets mapping for resolving -/// `@Native` assets at runtime. -/// -/// This kernel snapshot is concatenated to the [KernelSnapshotProgram] -/// inside [KernelSnapshot] to create the combined kernel snapshot. -class KernelSnapshotNativeAssets extends Target { - const KernelSnapshotNativeAssets(); - - @override - String get name => 'kernel_snapshot_native_assets'; - - @override - List get inputs => [ - const Source.pattern('{BUILD_DIR}/native_assets.yaml'), - ...const KernelSnapshotProgram().inputs, - ]; - - @override - List get outputs => const [ - Source.pattern('{BUILD_DIR}/${KernelSnapshotNativeAssets.dillName}'), - ]; - - @override - List get depfiles => const []; - - @override - List get dependencies => [ - const NativeAssets(), - ]; - - static const String dillName = 'native_assets.dill'; - - @override - Future build(Environment environment) async { - final File nativeAssetsFile = environment.buildDir.childFile('native_assets.yaml'); - final File dillFile = environment.buildDir.childFile(dillName); - - final YamlNode nativeAssetContents = loadYamlNode(await nativeAssetsFile.readAsString()); - final Object? nativeAssetsInYaml = (nativeAssetContents as Map)['native-assets']; - if (nativeAssetsInYaml is! Map || nativeAssetsInYaml.isEmpty) { - // Write an empty file to make concatenation a no-op. - // Write the file out to disk for caching. - await dillFile.writeAsBytes([]); - return; - } - - final KernelCompiler compiler = KernelCompiler( - fileSystem: environment.fileSystem, - logger: environment.logger, - processManager: environment.processManager, - artifacts: environment.artifacts, - fileSystemRoots: [], - ); - final String? buildModeEnvironment = environment.defines[kBuildMode]; - if (buildModeEnvironment == null) { - throw MissingDefineException(kBuildMode, 'kernel_snapshot'); - } - final String? targetPlatformEnvironment = environment.defines[kTargetPlatform]; - if (targetPlatformEnvironment == null) { - throw MissingDefineException(kTargetPlatform, 'kernel_snapshot'); - } - final BuildMode buildMode = BuildMode.fromCliName(buildModeEnvironment); - final File packageConfigFile = findPackageConfigFileOrDefault(environment.projectDir); - - final TargetPlatform targetPlatform = getTargetPlatformForName(targetPlatformEnvironment); - - final String? frontendServerStarterPath = environment.defines[kFrontendServerStarterPath]; - - final String nativeAssets = nativeAssetsFile.path; - if (!await nativeAssetsFile.exists()) { - throwToolExit("$nativeAssets doesn't exist."); - } - environment.logger.printTrace('Embedding native assets mapping $nativeAssets in kernel.'); - - final PackageConfig packageConfig = await loadPackageConfigWithLogging( - packageConfigFile, - logger: environment.logger, - ); - - final String dillPath = dillFile.path; - - final CompilerOutput? output = await compiler.compile( - sdkRoot: environment.artifacts.getArtifactPath( - Artifact.flutterPatchedSdkPath, - platform: targetPlatform, - mode: buildMode, - ), - aot: buildMode.isPrecompiled, - buildMode: buildMode, - trackWidgetCreation: false, - outputFilePath: dillPath, - packagesPath: packageConfigFile.path, - frontendServerStarterPath: frontendServerStarterPath, - packageConfig: packageConfig, - buildDir: environment.buildDir, - dartDefines: [], - nativeAssets: nativeAssets, - ); - if (output == null || output.errorCount != 0) { - throw Exception(); - } - } -} - -class KernelSnapshot extends Target { - const KernelSnapshot(); - - @override - String get name => 'kernel_snapshot'; - - @override - List get dependencies => const [ - KernelSnapshotProgram(), - KernelSnapshotNativeAssets(), - ]; - - @override - List get inputs => const [ - Source.pattern('{BUILD_DIR}/${KernelSnapshotProgram.dillName}'), - Source.pattern('{BUILD_DIR}/${KernelSnapshotNativeAssets.dillName}'), - ]; - - @override - List get outputs => []; - - static const String dillName = 'app.dill'; - - @override - Future build(Environment environment) async { - final File programDill = environment.buildDir.childFile( - KernelSnapshotProgram.dillName, - ); - final File nativeAssetsDill = environment.buildDir.childFile( - KernelSnapshotNativeAssets.dillName, - ); - final File dill = environment.buildDir.childFile(dillName); - await programDill.copy(dill.path); - await dill.writeAsBytes( - await nativeAssetsDill.readAsBytes(), - mode: FileMode.append, - ); - } -} - /// Supports compiling a dart kernel file to an ELF binary. abstract class AotElfBase extends Target { const AotElfBase(); diff --git a/packages/flutter_tools/lib/src/build_system/targets/ios.dart b/packages/flutter_tools/lib/src/build_system/targets/ios.dart index 6729aa2b3cf..2569e561197 100644 --- a/packages/flutter_tools/lib/src/build_system/targets/ios.dart +++ b/packages/flutter_tools/lib/src/build_system/targets/ios.dart @@ -12,6 +12,7 @@ import '../../base/file_system.dart'; import '../../base/io.dart'; import '../../base/process.dart'; import '../../build_info.dart'; +import '../../devfs.dart'; import '../../globals.dart' as globals; import '../../ios/mac.dart'; import '../../macos/xcode.dart'; @@ -24,6 +25,7 @@ import '../tools/shader_compiler.dart'; import 'assets.dart'; import 'common.dart'; import 'icon_tree_shaker.dart'; +import 'native_assets.dart'; /// Supports compiling a dart kernel file to an assembly file. /// @@ -464,6 +466,7 @@ abstract class IosAssetBundle extends Target { @override List get dependencies => const [ KernelSnapshot(), + InstallCodeAssets(), ]; @override @@ -551,6 +554,10 @@ abstract class IosAssetBundle extends Target { flutterProject.ios.infoPlist, flutterProject.ios.appFrameworkInfoPlist, ], + additionalContent: { + 'NativeAssetsManifest.json': + DevFSFileContent(environment.buildDir.childFile('native_assets.json')), + }, flavor: environment.defines[kFlavor], ); environment.depFileService.writeToFile( @@ -625,6 +632,7 @@ class ProfileIosApplicationBundle extends _IosAssetBundleWithDSYM { @override List get dependencies => const [ AotAssemblyProfile(), + InstallCodeAssets(), ]; } @@ -638,6 +646,7 @@ class ReleaseIosApplicationBundle extends _IosAssetBundleWithDSYM { @override List get dependencies => const [ AotAssemblyRelease(), + InstallCodeAssets(), ]; @override diff --git a/packages/flutter_tools/lib/src/build_system/targets/linux.dart b/packages/flutter_tools/lib/src/build_system/targets/linux.dart index 6f761f27b95..54d593f839a 100644 --- a/packages/flutter_tools/lib/src/build_system/targets/linux.dart +++ b/packages/flutter_tools/lib/src/build_system/targets/linux.dart @@ -15,6 +15,7 @@ import 'assets.dart'; import 'common.dart'; import 'desktop.dart'; import 'icon_tree_shaker.dart'; +import 'native_assets.dart'; /// The only files/subdirectories we care out. const List _kLinuxArtifacts = [ @@ -99,6 +100,7 @@ abstract class BundleLinuxAssets extends Target { @override List get dependencies => [ const KernelSnapshot(), + const InstallCodeAssets(), UnpackLinux(targetPlatform), ]; @@ -140,6 +142,8 @@ abstract class BundleLinuxAssets extends Target { buildMode: buildMode, additionalContent: { 'version.json': DevFSStringContent(versionInfo), + 'NativeAssetsManifest.json': + DevFSFileContent(environment.buildDir.childFile('native_assets.json')), }, ); environment.depFileService.writeToFile( diff --git a/packages/flutter_tools/lib/src/build_system/targets/localizations.dart b/packages/flutter_tools/lib/src/build_system/targets/localizations.dart index 2f5bdda24eb..b952e5b77e7 100644 --- a/packages/flutter_tools/lib/src/build_system/targets/localizations.dart +++ b/packages/flutter_tools/lib/src/build_system/targets/localizations.dart @@ -4,6 +4,7 @@ import '../../base/file_system.dart'; import '../../convert.dart'; +import '../../features.dart'; import '../../localizations/gen_l10n.dart'; import '../../localizations/localizations_utils.dart'; import '../build_system.dart'; @@ -56,7 +57,7 @@ class GenerateLocalizationsTarget extends Target { file: configFile, logger: environment.logger, defaultArbDir: defaultArbDir, - defaultSyntheticPackage: environment.useImplicitPubspecResolution, + defaultSyntheticPackage: !featureFlags.isExplicitPackageDependenciesEnabled, ); await generateLocalizations( logger: environment.logger, diff --git a/packages/flutter_tools/lib/src/build_system/targets/macos.dart b/packages/flutter_tools/lib/src/build_system/targets/macos.dart index 81cf6ae2f12..b7fdcd7d846 100644 --- a/packages/flutter_tools/lib/src/build_system/targets/macos.dart +++ b/packages/flutter_tools/lib/src/build_system/targets/macos.dart @@ -10,6 +10,7 @@ import '../../base/file_system.dart'; import '../../base/io.dart'; import '../../base/process.dart'; import '../../build_info.dart'; +import '../../devfs.dart'; import '../../globals.dart' as globals show xcode; import '../../reporting/reporting.dart'; import '../build_system.dart'; @@ -18,6 +19,7 @@ import '../exceptions.dart'; import 'assets.dart'; import 'common.dart'; import 'icon_tree_shaker.dart'; +import 'native_assets.dart'; /// Copy the macOS framework to the correct copy dir by invoking 'rsync'. /// @@ -489,6 +491,10 @@ abstract class MacOSBundleFlutterAssets extends Target { targetPlatform: TargetPlatform.darwin, buildMode: buildMode, flavor: environment.defines[kFlavor], + additionalContent: { + 'NativeAssetsManifest.json': + DevFSFileContent(environment.buildDir.childFile('native_assets.json')), + }, ); environment.depFileService.writeToFile( assetDepfile, @@ -591,6 +597,7 @@ class DebugMacOSBundleFlutterAssets extends MacOSBundleFlutterAssets { KernelSnapshot(), DebugMacOSFramework(), DebugUnpackMacOS(), + InstallCodeAssets(), ]; @override @@ -620,6 +627,7 @@ class ProfileMacOSBundleFlutterAssets extends MacOSBundleFlutterAssets { @override List get dependencies => const [ CompileMacOSFramework(), + InstallCodeAssets(), ProfileUnpackMacOS(), ]; @@ -647,6 +655,7 @@ class ReleaseMacOSBundleFlutterAssets extends MacOSBundleFlutterAssets { @override List get dependencies => const [ CompileMacOSFramework(), + InstallCodeAssets(), ReleaseUnpackMacOS(), ]; diff --git a/packages/flutter_tools/lib/src/build_system/targets/native_assets.dart b/packages/flutter_tools/lib/src/build_system/targets/native_assets.dart index 12efadc5dbf..47e97527922 100644 --- a/packages/flutter_tools/lib/src/build_system/targets/native_assets.dart +++ b/packages/flutter_tools/lib/src/build_system/targets/native_assets.dart @@ -3,12 +3,12 @@ // found in the LICENSE file. import 'package:meta/meta.dart'; -import 'package:native_assets_builder/native_assets_builder.dart'; import 'package:package_config/package_config_types.dart'; import '../../base/common.dart'; import '../../base/file_system.dart'; import '../../build_info.dart'; +import '../../convert.dart'; import '../../dart/package_map.dart'; import '../../isolated/native_assets/native_assets.dart'; import '../build_system.dart'; @@ -16,25 +16,9 @@ import '../depfile.dart'; import '../exceptions.dart'; import 'common.dart'; -/// Builds the right native assets for a Flutter app. -/// -/// The build mode and target architecture can be changed from the -/// native build project (Xcode etc.), so only `flutter assemble` has the -/// information about build-mode and target architecture. -/// Invocations of flutter_tools other than `flutter assemble` are dry runs. -/// -/// This step needs to be consistent with the dry run invocations in `flutter -/// run`s so that the kernel mapping of asset id to dylib lines up after hot -/// restart. -/// -/// [KernelSnapshot] depends on this target. We produce a native_assets.yaml -/// here, and embed that mapping inside the kernel snapshot. -/// -/// The build always produces a valid native_assets.yaml and a native_assets.d -/// even if there are no native assets. This way the caching logic won't try to -/// rebuild. -class NativeAssets extends Target { - const NativeAssets({ +/// Runs the dart build of the app. +abstract class DartBuild extends Target { + const DartBuild({ @visibleForTesting FlutterNativeAssetsBuildRunner? buildRunner, }) : _buildRunner = buildRunner; @@ -42,26 +26,20 @@ class NativeAssets extends Target { @override Future build(Environment environment) async { - final String? nativeAssetsEnvironment = environment.defines[kNativeAssets]; final FileSystem fileSystem = environment.fileSystem; - final Uri nativeAssetsFileUri = environment.buildDir.childFile('native_assets.yaml').uri; + final String? nativeAssetsEnvironment = environment.defines[kNativeAssets]; final DartBuildResult result; if (nativeAssetsEnvironment == 'false') { result = const DartBuildResult.empty(); - await writeNativeAssetsYaml(KernelAssets(), nativeAssetsFileUri, fileSystem); } else { - final String? targetPlatformEnvironment = environment.defines[kTargetPlatform]; - if (targetPlatformEnvironment == null) { - throw MissingDefineException(kTargetPlatform, name); - } - final TargetPlatform targetPlatform = getTargetPlatformForName(targetPlatformEnvironment); - final Uri projectUri = environment.projectDir.uri; + final TargetPlatform targetPlatform = _getTargetPlatformFromEnvironment(environment, name); final PackageConfig packageConfig = await loadPackageConfigWithLogging( fileSystem.file(environment.packageConfigPath), logger: environment.logger, ); + final Uri projectUri = environment.projectDir.uri; final FlutterNativeAssetsBuildRunner buildRunner = _buildRunner ?? FlutterNativeAssetsBuildRunnerImpl( projectUri, @@ -70,48 +48,41 @@ class NativeAssets extends Target { fileSystem, environment.logger, ); - - (result, _) = await runFlutterSpecificDartBuild( + result = await runFlutterSpecificDartBuild( environmentDefines: environment.defines, buildRunner: buildRunner, targetPlatform: targetPlatform, projectUri: projectUri, - nativeAssetsYamlUri : nativeAssetsFileUri, fileSystem: fileSystem, ); } + final File dartBuildResultJsonFile = environment.buildDir.childFile(dartBuildResultFilename); + if (!dartBuildResultJsonFile.parent.existsSync()) { + dartBuildResultJsonFile.parent.createSync(recursive: true); + } + dartBuildResultJsonFile.writeAsStringSync(json.encode(result.toJson())); + final Depfile depfile = Depfile( [ for (final Uri dependency in result.dependencies) fileSystem.file(dependency), ], [ - fileSystem.file(nativeAssetsFileUri), + fileSystem.file(dartBuildResultJsonFile), ], ); - final File outputDepfile = environment.buildDir.childFile('native_assets.d'); + final File outputDepfile = environment.buildDir.childFile(depFilename); if (!outputDepfile.parent.existsSync()) { outputDepfile.parent.createSync(recursive: true); } environment.depFileService.writeToFile(depfile, outputDepfile); - if (!await fileSystem.file(nativeAssetsFileUri).exists()) { - throwToolExit("${nativeAssetsFileUri.path} doesn't exist."); - } if (!await outputDepfile.exists()) { throwToolExit("${outputDepfile.path} doesn't exist."); } } @override - List get depfiles => [ - 'native_assets.d', - ]; - - @override - List get dependencies => const [ - // In AOT, depends on tree-shaking information (resources.json) from compiling dart. - KernelSnapshotProgram(), - ]; + List get depfiles => const [depFilename]; @override List get inputs => const [ @@ -122,10 +93,104 @@ class NativeAssets extends Target { ]; @override - String get name => 'native_assets'; + String get name => 'dart_build'; @override List get outputs => const [ - Source.pattern('{BUILD_DIR}/native_assets.yaml'), + Source.pattern('{BUILD_DIR}/$dartBuildResultFilename'), + ]; + + /// Dependent build [Target]s can use this to consume the result of the + /// [DartBuild] target. + static Future loadBuildResult(Environment environment) async { + final File dartBuildResultJsonFile = environment.buildDir.childFile(DartBuild.dartBuildResultFilename); + return DartBuildResult.fromJson(json.decode(dartBuildResultJsonFile.readAsStringSync()) as Map); + } + + static const String dartBuildResultFilename = 'dart_build_result.json'; + static const String depFilename = 'dart_build.d'; +} + +class DartBuildForNative extends DartBuild { + const DartBuildForNative({@visibleForTesting super.buildRunner}); + + @override + List get dependencies => const [ + KernelSnapshot(), ]; } + +/// Installs the code assets from a [DartBuild] Flutter app. +/// +/// The build mode and target architecture can be changed from the +/// native build project (Xcode etc.), so only `flutter assemble` has the +/// information about build-mode and target architecture. +class InstallCodeAssets extends Target { + const InstallCodeAssets(); + + @override + Future build(Environment environment) async { + final Uri projectUri = environment.projectDir.uri; + final FileSystem fileSystem = environment.fileSystem; + final TargetPlatform targetPlatform = _getTargetPlatformFromEnvironment(environment, name); + + // We fetch the result from the [DartBuild]. + final DartBuildResult dartBuildResult = await DartBuild.loadBuildResult(environment); + + // And install/copy the code assets to the right place and create a + // native_asset.yaml that can be used by the final AOT compilation. + final Uri nativeAssetsFileUri = environment.buildDir.childFile(nativeAssetsFilename).uri; + await installCodeAssets(dartBuildResult: dartBuildResult, environmentDefines: environment.defines, + targetPlatform: targetPlatform, projectUri: projectUri, fileSystem: fileSystem, + nativeAssetsFileUri: nativeAssetsFileUri); + assert(await fileSystem.file(nativeAssetsFileUri).exists()); + + final Depfile depfile = Depfile( + [ + for (final Uri file in dartBuildResult.filesToBeBundled) fileSystem.file(file), + ], + [ + fileSystem.file(nativeAssetsFileUri), + ], + ); + final File outputDepfile = environment.buildDir.childFile(depFilename); + environment.depFileService.writeToFile(depfile, outputDepfile); + if (!await outputDepfile.exists()) { + throwToolExit("${outputDepfile.path} doesn't exist."); + } + } + + @override + List get depfiles => [depFilename]; + + @override + List get dependencies => const [ + DartBuildForNative(), + ]; + + @override + List get inputs => const [ + Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/native_assets.dart'), + // If different packages are resolved, different native assets might need to be built. + Source.pattern('{WORKSPACE_DIR}/.dart_tool/package_config_subset'), + ]; + + @override + String get name => 'install_code_assets'; + + @override + List get outputs => const [ + Source.pattern('{BUILD_DIR}/$nativeAssetsFilename'), + ]; + + static const String nativeAssetsFilename = 'native_assets.json'; + static const String depFilename = 'install_code_assets.d'; +} + +TargetPlatform _getTargetPlatformFromEnvironment(Environment environment, String name) { + final String? targetPlatformEnvironment = environment.defines[kTargetPlatform]; + if (targetPlatformEnvironment == null) { + throw MissingDefineException(kTargetPlatform, name); + } + return getTargetPlatformForName(targetPlatformEnvironment); +} diff --git a/packages/flutter_tools/lib/src/build_system/targets/windows.dart b/packages/flutter_tools/lib/src/build_system/targets/windows.dart index 2aadcf12b17..599ea00243a 100644 --- a/packages/flutter_tools/lib/src/build_system/targets/windows.dart +++ b/packages/flutter_tools/lib/src/build_system/targets/windows.dart @@ -5,6 +5,7 @@ import '../../artifacts.dart'; import '../../base/file_system.dart'; import '../../build_info.dart'; +import '../../devfs.dart'; import '../build_system.dart'; import '../depfile.dart'; import '../exceptions.dart'; @@ -12,6 +13,7 @@ import 'assets.dart'; import 'common.dart'; import 'desktop.dart'; import 'icon_tree_shaker.dart'; +import 'native_assets.dart'; /// The only files/subdirectories we care about. const List _kWindowsArtifacts = [ @@ -105,6 +107,7 @@ abstract class BundleWindowsAssets extends Target { @override List get dependencies => [ const KernelSnapshot(), + const InstallCodeAssets(), UnpackWindows(targetPlatform), ]; @@ -143,6 +146,10 @@ abstract class BundleWindowsAssets extends Target { outputDirectory, targetPlatform: targetPlatform, buildMode: buildMode, + additionalContent: { + 'NativeAssetsManifest.json': + DevFSFileContent(environment.buildDir.childFile('native_assets.json')), + }, ); environment.depFileService.writeToFile( depfile, diff --git a/packages/flutter_tools/lib/src/build_system/tools/shader_compiler.dart b/packages/flutter_tools/lib/src/build_system/tools/shader_compiler.dart index bef6474cabb..34aaaf812e7 100644 --- a/packages/flutter_tools/lib/src/build_system/tools/shader_compiler.dart +++ b/packages/flutter_tools/lib/src/build_system/tools/shader_compiler.dart @@ -115,7 +115,7 @@ class ShaderCompiler { case TargetPlatform.linux_arm64: case TargetPlatform.windows_x64: case TargetPlatform.windows_arm64: - return ['--sksl', '--runtime-stage-gles', '--runtime-stage-vulkan']; + return ['--sksl', '--runtime-stage-gles', '--runtime-stage-gles3', '--runtime-stage-vulkan']; case TargetPlatform.ios: case TargetPlatform.darwin: diff --git a/packages/flutter_tools/lib/src/bundle_builder.dart b/packages/flutter_tools/lib/src/bundle_builder.dart index 632ddcea6bd..effda740a51 100644 --- a/packages/flutter_tools/lib/src/bundle_builder.dart +++ b/packages/flutter_tools/lib/src/bundle_builder.dart @@ -37,7 +37,6 @@ class BundleBuilder { Future build({ required TargetPlatform platform, required BuildInfo buildInfo, - required bool useImplicitPubspecResolution, FlutterProject? project, String? mainPath, String manifestPath = defaultManifestPath, @@ -80,7 +79,6 @@ class BundleBuilder { analytics: globals.analytics, platform: globals.platform, generateDartPluginRegistry: true, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); final Target target = buildInfo.mode == BuildMode.debug ? globals.buildTargets.copyFlutterBundle diff --git a/packages/flutter_tools/lib/src/commands/assemble.dart b/packages/flutter_tools/lib/src/commands/assemble.dart index 3fc926f89d9..69fc1432a6b 100644 --- a/packages/flutter_tools/lib/src/commands/assemble.dart +++ b/packages/flutter_tools/lib/src/commands/assemble.dart @@ -26,7 +26,6 @@ import '../globals.dart' as globals; import '../project.dart'; import '../reporting/reporting.dart'; import '../runner/flutter_command.dart'; -import '../runner/flutter_command_runner.dart'; /// All currently implemented targets. List _kDefaultTargets = [ @@ -253,7 +252,6 @@ class AssembleCommand extends FlutterCommand { ? null : globals.flutterVersion.engineRevision, generateDartPluginRegistry: true, - useImplicitPubspecResolution: globalResults!.flag(FlutterGlobalOptions.kImplicitPubspecResolution), ); return result; } @@ -312,6 +310,14 @@ class AssembleCommand extends FlutterCommand { "Try re-running 'flutter build ios' or the appropriate build command." ); } + if (deferredTargets.isNotEmpty) { + // Record to analytics that DeferredComponents is being used. + globals.analytics.send(Event.flutterBuildInfo( + label: 'assemble-deferred-components', + buildType: 'android', + settings: deferredTargets.map((Target t) => t.name).join(','), + )); + } if (_flutterProject.manifest.deferredComponents != null && decodedDefines.contains('validate-deferred-components=true') && deferredTargets.isNotEmpty diff --git a/packages/flutter_tools/lib/src/commands/attach.dart b/packages/flutter_tools/lib/src/commands/attach.dart index b149f72000f..7945925fdd0 100644 --- a/packages/flutter_tools/lib/src/commands/attach.dart +++ b/packages/flutter_tools/lib/src/commands/attach.dart @@ -31,7 +31,6 @@ import '../run_cold.dart'; import '../run_hot.dart'; import '../runner/flutter_command.dart'; import '../runner/flutter_command_runner.dart'; -import '../vmservice.dart'; /// A Flutter-command that attaches to applications that have been launched /// without `flutter run`. @@ -69,7 +68,6 @@ class AttachCommand extends FlutterCommand { required Platform platform, required ProcessInfo processInfo, required FileSystem fileSystem, - HotRunnerNativeAssetsBuilder? nativeAssetsBuilder, }) : _hotRunnerFactory = hotRunnerFactory ?? HotRunnerFactory(), _stdio = stdio, _logger = logger, @@ -77,8 +75,7 @@ class AttachCommand extends FlutterCommand { _signals = signals, _platform = platform, _processInfo = processInfo, - _fileSystem = fileSystem, - _nativeAssetsBuilder = nativeAssetsBuilder { + _fileSystem = fileSystem { addBuildModeFlags(verboseHelp: verboseHelp, defaultToRelease: false, excludeRelease: true); usesTargetOption(); usesPortOptions(verboseHelp: verboseHelp); @@ -150,7 +147,6 @@ class AttachCommand extends FlutterCommand { final Platform _platform; final ProcessInfo _processInfo; final FileSystem _fileSystem; - final HotRunnerNativeAssetsBuilder? _nativeAssetsBuilder; @override final String name = 'attach'; @@ -280,7 +276,6 @@ known, it can be explicitly provided to attach via the command-line, e.g. ? _logger : NotifyingLogger(verbose: _logger.isVerbose, parent: _logger), logToStdout: true, - useImplicitPubspecResolution: globalResults!.flag(FlutterGlobalOptions.kImplicitPubspecResolution), ) : null; @@ -350,7 +345,6 @@ known, it can be explicitly provided to attach via the command-line, e.g. device: device, flutterProject: flutterProject, usesIpv6: usesIpv6, - nativeAssetsBuilder: _nativeAssetsBuilder, ); late AppInstance app; try { @@ -374,7 +368,7 @@ known, it can be explicitly provided to attach via the command-line, e.g. } on Exception catch (error) { throwToolExit(error.toString()); } - result = await app.runner!.waitForAppToFinish(); + result = await app.runner.waitForAppToFinish(); return; } while (true) { @@ -383,7 +377,6 @@ known, it can be explicitly provided to attach via the command-line, e.g. device: device, flutterProject: flutterProject, usesIpv6: usesIpv6, - nativeAssetsBuilder: _nativeAssetsBuilder, ); final Completer onAppStart = Completer.sync(); TerminalHandler? terminalHandler; @@ -415,7 +408,7 @@ known, it can be explicitly provided to attach via the command-line, e.g. _logger.printStatus('Waiting for a new connection from Flutter on ${device.name}...'); } } on RPCError catch (err) { - if (err.code == RPCErrorCodes.kServiceDisappeared || + if (err.code == RPCErrorKind.kServiceDisappeared.code || err.message.contains('Service connection disposed')) { throwToolExit('Lost connection to device.'); } @@ -440,7 +433,6 @@ known, it can be explicitly provided to attach via the command-line, e.g. required Device device, required FlutterProject flutterProject, required bool usesIpv6, - required HotRunnerNativeAssetsBuilder? nativeAssetsBuilder, }) async { final BuildInfo buildInfo = await getBuildInfo(); @@ -467,7 +459,6 @@ known, it can be explicitly provided to attach via the command-line, e.g. printDtd: boolArg(FlutterGlobalOptions.kPrintDtd, global: true), ); - final bool useImplicitPubspecResolution = globalResults!.flag(FlutterGlobalOptions.kImplicitPubspecResolution); return buildInfo.isDebug ? _hotRunnerFactory.build( flutterDevices, @@ -478,15 +469,12 @@ known, it can be explicitly provided to attach via the command-line, e.g. dillOutputPath: stringArg('output-dill'), flutterProject: flutterProject, nativeAssetsYamlFile: stringArg(FlutterOptions.kNativeAssetsYamlFile), - nativeAssetsBuilder: _nativeAssetsBuilder, analytics: analytics, - useImplicitPubspecResolution: useImplicitPubspecResolution, ) : ColdRunner( flutterDevices, target: targetFile, debuggingOptions: debuggingOptions, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); } @@ -512,8 +500,6 @@ class HotRunnerFactory { bool stayResident = true, FlutterProject? flutterProject, String? nativeAssetsYamlFile, - required HotRunnerNativeAssetsBuilder? nativeAssetsBuilder, - required bool useImplicitPubspecResolution, required Analytics analytics, }) => HotRunner( devices, @@ -526,8 +512,6 @@ class HotRunnerFactory { dillOutputPath: dillOutputPath, stayResident: stayResident, nativeAssetsYamlFile: nativeAssetsYamlFile, - nativeAssetsBuilder: nativeAssetsBuilder, analytics: analytics, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); } diff --git a/packages/flutter_tools/lib/src/commands/build_appbundle.dart b/packages/flutter_tools/lib/src/commands/build_appbundle.dart index d0a6188293e..ca58c4a2e2a 100644 --- a/packages/flutter_tools/lib/src/commands/build_appbundle.dart +++ b/packages/flutter_tools/lib/src/commands/build_appbundle.dart @@ -143,6 +143,13 @@ class BuildAppBundleCommand extends BuildSubCommand { // Do all setup verification that doesn't involve loading units. Checks that // require generated loading units are done after gen_snapshot in assemble. final List? deferredComponents = FlutterProject.current().manifest.deferredComponents; + if (deferredComponents != null && boolArg('deferred-components')) { + // Record to analytics that DeferredComponents is being used. + globals.analytics.send(Event.flutterBuildInfo( + label: 'build-appbundle-deferred-components', + buildType: 'android', + )); + } if (deferredComponents != null && boolArg('deferred-components') && boolArg('validate-deferred-components') && !boolArg('debug')) { final DeferredComponentsPrebuildValidator validator = DeferredComponentsPrebuildValidator( project.directory, diff --git a/packages/flutter_tools/lib/src/commands/build_bundle.dart b/packages/flutter_tools/lib/src/commands/build_bundle.dart index fbfa1f49a19..82470cf6071 100644 --- a/packages/flutter_tools/lib/src/commands/build_bundle.dart +++ b/packages/flutter_tools/lib/src/commands/build_bundle.dart @@ -13,7 +13,6 @@ import '../globals.dart' as globals; import '../project.dart'; import '../reporting/reporting.dart'; import '../runner/flutter_command.dart'; -import '../runner/flutter_command_runner.dart'; import 'build.dart'; class BuildBundleCommand extends BuildSubCommand { @@ -150,7 +149,6 @@ class BuildBundleCommand extends BuildSubCommand { depfilePath: stringArg('depfile'), assetDirPath: stringArg('asset-dir'), buildNativeAssets: false, - useImplicitPubspecResolution: globalResults!.flag(FlutterGlobalOptions.kImplicitPubspecResolution), ); return FlutterCommandResult.success(); } diff --git a/packages/flutter_tools/lib/src/commands/build_ios.dart b/packages/flutter_tools/lib/src/commands/build_ios.dart index 3401776c529..9b10fa9316b 100644 --- a/packages/flutter_tools/lib/src/commands/build_ios.dart +++ b/packages/flutter_tools/lib/src/commands/build_ios.dart @@ -773,11 +773,9 @@ abstract class _BuildIOSSubCommand extends BuildSubCommand { 'A summary of your iOS bundle analysis can be found at: ${outputFile.path}', ); - // DevTools expects a file path relative to the .flutter-devtools/ dir. - final String relativeAppSizePath = outputFile.path.split('.flutter-devtools/').last.trim(); globals.printStatus( '\nTo analyze your app size in Dart DevTools, run the following command:\n' - 'dart devtools --appSizeBase=$relativeAppSizePath' + 'dart devtools --appSizeBase=${outputFile.path}' ); } diff --git a/packages/flutter_tools/lib/src/commands/build_ios_framework.dart b/packages/flutter_tools/lib/src/commands/build_ios_framework.dart index 3398ba78aa8..795f89bd3c0 100644 --- a/packages/flutter_tools/lib/src/commands/build_ios_framework.dart +++ b/packages/flutter_tools/lib/src/commands/build_ios_framework.dart @@ -21,7 +21,6 @@ import '../flutter_plugins.dart'; import '../globals.dart' as globals; import '../macos/cocoapod_utils.dart'; import '../runner/flutter_command.dart' show DevelopmentArtifact, FlutterCommandResult; -import '../runner/flutter_command_runner.dart'; import '../version.dart'; import 'build.dart'; @@ -287,6 +286,8 @@ class BuildIOSFrameworkCommand extends BuildFrameworkCommand { '- .DS_Store', '--filter', '- native_assets.yaml', + '--filter', + '- native_assets.json', nativeAssetsDirectory.path, modeDirectory.path, ]); @@ -461,7 +462,6 @@ end ? null : globals.flutterVersion.engineRevision, generateDartPluginRegistry: true, - useImplicitPubspecResolution: globalResults!.flag(FlutterGlobalOptions.kImplicitPubspecResolution), ); Target target; // Always build debug for simulator. diff --git a/packages/flutter_tools/lib/src/commands/build_macos_framework.dart b/packages/flutter_tools/lib/src/commands/build_macos_framework.dart index 5a8c61f31d2..f99158891be 100644 --- a/packages/flutter_tools/lib/src/commands/build_macos_framework.dart +++ b/packages/flutter_tools/lib/src/commands/build_macos_framework.dart @@ -19,7 +19,6 @@ import '../flutter_plugins.dart'; import '../globals.dart' as globals; import '../macos/cocoapod_utils.dart'; import '../runner/flutter_command.dart' show DevelopmentArtifact, FlutterCommandResult; -import '../runner/flutter_command_runner.dart'; import '../version.dart'; import 'build_ios_framework.dart'; @@ -119,6 +118,8 @@ class BuildMacOSFrameworkCommand extends BuildFrameworkCommand { '- .DS_Store', '--filter', '- native_assets.yaml', + '--filter', + '- native_assets.json', nativeAssetsDirectory.path, modeDirectory.path, ]); @@ -240,7 +241,6 @@ end analytics: globals.analytics, engineVersion: globals.artifacts!.usesLocalArtifacts ? null : globals.flutterVersion.engineRevision, generateDartPluginRegistry: true, - useImplicitPubspecResolution: globalResults!.flag(FlutterGlobalOptions.kImplicitPubspecResolution), ); Target target; // Always build debug for simulator. diff --git a/packages/flutter_tools/lib/src/commands/build_web.dart b/packages/flutter_tools/lib/src/commands/build_web.dart index d189c1bbb4b..8aba1bc81c2 100644 --- a/packages/flutter_tools/lib/src/commands/build_web.dart +++ b/packages/flutter_tools/lib/src/commands/build_web.dart @@ -10,7 +10,6 @@ import '../features.dart'; import '../globals.dart' as globals; import '../runner/flutter_command.dart' show DevelopmentArtifact, FlutterCommandResult, FlutterOptions; -import '../runner/flutter_command_runner.dart'; import '../web/compile.dart'; import '../web/file_generators/flutter_service_worker_js.dart'; import '../web/web_constants.dart'; @@ -52,7 +51,6 @@ class BuildWebCommand extends BuildSubCommand { allowed: ServiceWorkerStrategy.values.map((ServiceWorkerStrategy e) => e.cliName), allowedHelp: CliEnum.allowedHelp(ServiceWorkerStrategy.values), ); - usesWebRendererOption(); usesWebResourcesCdnFlag(); // @@ -142,20 +140,23 @@ class BuildWebCommand extends BuildSubCommand { ? int.parse(dart2jsOptimizationLevelValue.substring(1)) : optimizationLevel; - final String? webRendererString = stringArg(FlutterOptions.kWebRendererFlag); - final WebRendererMode? webRenderer = webRendererString == null - ? null - : WebRendererMode.values.byName(webRendererString); + final List dartDefines = extractDartDefines( + defineConfigJsonMap: extractDartDefineConfigJsonMap() + ); + final bool useWasm = boolArg(FlutterOptions.kWebWasmFlag); + // See also: RunCommandBase.webRenderer and TestCommand.webRenderer. + final WebRendererMode webRenderer = WebRendererMode.fromDartDefines(dartDefines, useWasm: useWasm); final bool sourceMaps = boolArg('source-maps'); final List compilerConfigs; - if (webRenderer != null && webRenderer.isDeprecated) { + if (webRenderer.isDeprecated) { globals.logger.printWarning(webRenderer.deprecationWarning); } - if (boolArg(FlutterOptions.kWebWasmFlag)) { - if (webRenderer != null) { - throwToolExit('"--${FlutterOptions.kWebRendererFlag}" cannot be combined with "--${FlutterOptions.kWebWasmFlag}"'); + + if (useWasm) { + if (webRenderer != WebRendererMode.getDefault(useWasm: true)) { + throwToolExit('Do not attempt to set a web renderer when using "--${FlutterOptions.kWebWasmFlag}"'); } globals.logger.printBox( title: 'New feature', @@ -186,7 +187,7 @@ class BuildWebCommand extends BuildSubCommand { nativeNullAssertions: boolArg('native-null-assertions'), noFrequencyBasedMinification: boolArg('no-frequency-based-minification'), sourceMaps: sourceMaps, - renderer: webRenderer ?? WebRendererMode.defaultForJs, + renderer: webRenderer, )]; } @@ -227,7 +228,6 @@ class BuildWebCommand extends BuildSubCommand { flutterVersion: globals.flutterVersion, usage: globals.flutterUsage, analytics: globals.analytics, - useImplicitPubspecResolution: globalResults!.flag(FlutterGlobalOptions.kImplicitPubspecResolution), ); await webBuilder.buildWeb( project, diff --git a/packages/flutter_tools/lib/src/commands/channel.dart b/packages/flutter_tools/lib/src/commands/channel.dart index 667e5a7c3ed..51289433c5c 100644 --- a/packages/flutter_tools/lib/src/commands/channel.dart +++ b/packages/flutter_tools/lib/src/commands/channel.dart @@ -29,13 +29,21 @@ class ChannelCommand extends FlutterCommand { } @override - final String name = 'channel'; + String get name => 'channel'; @override - final String description = 'List or switch Flutter channels.'; + String get description => 'List or switch Flutter channels.\n' + '\n' + 'Common commands:\n' + '\n' + ' flutter channel\n' + ' List Flutter channels.\n' + '\n' + ' flutter channel main\n' + " Switch to Flutter's main channel."; @override - final String category = FlutterCommandCategory.sdk; + String get category => FlutterCommandCategory.sdk; @override String get invocation => '${runner?.executableName} $name []'; diff --git a/packages/flutter_tools/lib/src/commands/create.dart b/packages/flutter_tools/lib/src/commands/create.dart index 39386f45c64..e93cb96fd86 100644 --- a/packages/flutter_tools/lib/src/commands/create.dart +++ b/packages/flutter_tools/lib/src/commands/create.dart @@ -26,7 +26,6 @@ import '../macos/swift_packages.dart'; import '../project.dart'; import '../reporting/reporting.dart'; import '../runner/flutter_command.dart'; -import '../runner/flutter_command_runner.dart'; import 'create_base.dart'; const String kPlatformHelp = @@ -36,10 +35,73 @@ const String kPlatformHelp = 'When adding platforms to a plugin project, the pubspec.yaml will be updated with the requested platform. ' 'Adding desktop platforms requires the corresponding desktop config setting to be enabled.'; -class CreateCommand extends CreateBase { - CreateCommand({ - super.verboseHelp = false, - }) { +class CreateCommand extends FlutterCommand with CreateBase { + CreateCommand({bool verboseHelp = false}) { + addPubOptions(); + argParser.addFlag( + 'with-driver-test', + help: '(deprecated) Historically, this added a flutter_driver dependency and generated a ' + 'sample "flutter drive" test. Now it does nothing. Consider using the ' + '"integration_test" package: https://pub.dev/packages/integration_test', + hide: !verboseHelp, + ); + argParser.addFlag( + 'overwrite', + help: 'When performing operations, overwrite existing files.', + ); + argParser.addOption( + 'description', + defaultsTo: 'A new Flutter project.', + help: + 'The description to use for your new Flutter project. This string ends up in the pubspec.yaml file.', + ); + argParser.addOption( + 'org', + defaultsTo: 'com.example', + help: + 'The organization responsible for your new Flutter project, in reverse domain name notation. ' + 'This string is used in Java package names and as prefix in the iOS bundle identifier.', + ); + argParser.addOption( + 'project-name', + help: + 'The project name for this new Flutter project. This must be a valid dart package name.', + ); + argParser.addOption( + 'ios-language', + abbr: 'i', + defaultsTo: 'swift', + allowed: ['objc', 'swift'], + help: '(deprecated) The language to use for iOS-specific code, either Swift (recommended) or Objective-C (legacy).', + hide: !verboseHelp, + ); + argParser.addOption( + 'android-language', + abbr: 'a', + defaultsTo: 'kotlin', + allowed: ['java', 'kotlin'], + help: 'The language to use for Android-specific code, either Kotlin (recommended) or Java (legacy).', + ); + argParser.addFlag( + 'skip-name-checks', + help: + 'Allow the creation of applications and plugins with invalid names. ' + 'This is only intended to enable testing of the tool itself.', + hide: !verboseHelp, + ); + argParser.addFlag( + 'implementation-tests', + help: + 'Include implementation tests that verify the template functions correctly. ' + 'This is only intended to enable testing of the tool itself.', + hide: !verboseHelp, + ); + argParser.addOption( + 'initial-create-revision', + help: 'The Flutter SDK git commit hash to store in .migrate_config. This parameter is used by the tool ' + 'internally and should generally not be used manually.', + hide: !verboseHelp, + ); addPlatformsOptions(customHelp: kPlatformHelp); argParser.addOption( 'template', @@ -438,12 +500,12 @@ class CreateCommand extends CreateBase { pubContext = PubContext.createPackage; } - if (boolArg('pub')) { + if (shouldCallPubGet) { final FlutterProject project = FlutterProject.fromDirectory(relativeDir); await pub.get( context: pubContext, project: project, - offline: boolArg('offline'), + offline: offline, outputMode: PubOutputMode.summaryOnly, ); // Setting `includeIos` etc to false as with FlutterProjectType.package @@ -459,7 +521,6 @@ class CreateCommand extends CreateBase { macOSPlatform: includeMacos, windowsPlatform: includeWindows, webPlatform: includeWeb, - useImplicitPubspecResolution: boolArg(FlutterGlobalOptions.kImplicitPubspecResolution, global: true), ); } } diff --git a/packages/flutter_tools/lib/src/commands/create_base.dart b/packages/flutter_tools/lib/src/commands/create_base.dart index 4cde6ffacc8..c69b868e365 100644 --- a/packages/flutter_tools/lib/src/commands/create_base.dart +++ b/packages/flutter_tools/lib/src/commands/create_base.dart @@ -21,7 +21,6 @@ import '../flutter_project_metadata.dart'; import '../globals.dart' as globals; import '../project.dart'; import '../runner/flutter_command.dart'; -import '../runner/flutter_command_runner.dart'; import '../template.dart'; const List _kAvailablePlatforms = [ @@ -49,96 +48,15 @@ const String _kDefaultPlatformArgumentHelp = 'Platform folders (e.g. android/) will be generated in the target project. ' 'Adding desktop platforms requires the corresponding desktop config setting to be enabled.'; -/// Common behavior for `flutter create` commands. -abstract class CreateBase extends FlutterCommand { - CreateBase({ - required bool verboseHelp, - }) { - argParser.addFlag( - 'pub', - defaultsTo: true, - help: - 'Whether to run "flutter pub get" after the project has been created.', - ); - argParser.addFlag( - 'offline', - help: - 'When "flutter pub get" is run by the create command, this indicates ' - 'whether to run it in offline mode or not. In offline mode, it will need to ' - 'have all dependencies already available in the pub cache to succeed.', - ); - argParser.addFlag( - 'with-driver-test', - help: '(deprecated) Historically, this added a flutter_driver dependency and generated a ' - 'sample "flutter drive" test. Now it does nothing. Consider using the ' - '"integration_test" package: https://pub.dev/packages/integration_test', - hide: !verboseHelp, - ); - argParser.addFlag( - 'overwrite', - help: 'When performing operations, overwrite existing files.', - ); - argParser.addOption( - 'description', - defaultsTo: 'A new Flutter project.', - help: - 'The description to use for your new Flutter project. This string ends up in the pubspec.yaml file.', - ); - argParser.addOption( - 'org', - defaultsTo: 'com.example', - help: - 'The organization responsible for your new Flutter project, in reverse domain name notation. ' - 'This string is used in Java package names and as prefix in the iOS bundle identifier.', - ); - argParser.addOption( - 'project-name', - help: - 'The project name for this new Flutter project. This must be a valid dart package name.', - ); - argParser.addOption( - 'ios-language', - abbr: 'i', - defaultsTo: 'swift', - allowed: ['objc', 'swift'], - help: '(deprecated) The language to use for iOS-specific code, either Swift (recommended) or Objective-C (legacy).', - hide: !verboseHelp, - ); - argParser.addOption( - 'android-language', - abbr: 'a', - defaultsTo: 'kotlin', - allowed: ['java', 'kotlin'], - help: 'The language to use for Android-specific code, either Kotlin (recommended) or Java (legacy).', - ); - argParser.addFlag( - 'skip-name-checks', - help: - 'Allow the creation of applications and plugins with invalid names. ' - 'This is only intended to enable testing of the tool itself.', - hide: !verboseHelp, - ); - argParser.addFlag( - 'implementation-tests', - help: - 'Include implementation tests that verify the template functions correctly. ' - 'This is only intended to enable testing of the tool itself.', - hide: !verboseHelp, - ); - argParser.addOption( - 'initial-create-revision', - help: 'The Flutter SDK git commit hash to store in .migrate_config. This parameter is used by the tool ' - 'internally and should generally not be used manually.', - hide: !verboseHelp, - ); - } - +/// Common behavior for `flutter create` and `flutter widget-preview start` commands. +mixin CreateBase on FlutterCommand { /// Pattern for a Windows file system drive (e.g. "D:"). /// /// `dart:io` does not recognize strings matching this pattern as absolute /// paths, as they have no top level back-slash; however, users often specify /// this @visibleForTesting + @protected static final RegExp kWindowsDrivePattern = RegExp(r'^[a-zA-Z]:$'); /// The output directory of the command. @@ -163,6 +81,35 @@ abstract class CreateBase extends FlutterCommand { return globals.fs.path.normalize(projectDir.absolute.path); } + @protected + bool get shouldCallPubGet { + return boolArg('pub'); + } + + @protected + bool get offline { + return boolArg('offline'); + } + + /// Adds `--pub` and `--offline` options. + @protected + void addPubOptions() { + argParser + ..addFlag( + 'pub', + defaultsTo: true, + help: + 'Whether to run "flutter pub get" after the project has been created.', + ) + ..addFlag( + 'offline', + help: + 'When "flutter pub get" is run by the create command, this indicates ' + 'whether to run it in offline mode or not. In offline mode, it will need to ' + 'have all dependencies already available in the pub cache to succeed.', + ); + } + /// Adds a `--platforms` argument. /// /// The help message of the argument is replaced with `customHelp` if `customHelp` is not null. @@ -559,7 +506,7 @@ abstract class CreateBase extends FlutterCommand { final bool windowsPlatform = templateContext['windows'] as bool? ?? false; final bool webPlatform = templateContext['web'] as bool? ?? false; - if (boolArg('pub')) { + if (shouldCallPubGet) { final Environment environment = Environment( artifacts: globals.artifacts!, logger: globals.logger, @@ -575,7 +522,6 @@ abstract class CreateBase extends FlutterCommand { projectDir: project.directory, packageConfigPath: packageConfigPath(), generateDartPluginRegistry: true, - useImplicitPubspecResolution: globalResults!.flag(FlutterGlobalOptions.kImplicitPubspecResolution), ); // Generate the l10n synthetic package that will be injected into the diff --git a/packages/flutter_tools/lib/src/commands/custom_devices.dart b/packages/flutter_tools/lib/src/commands/custom_devices.dart index 2079881a6c7..9ffe6e8234b 100644 --- a/packages/flutter_tools/lib/src/commands/custom_devices.dart +++ b/packages/flutter_tools/lib/src/commands/custom_devices.dart @@ -378,7 +378,6 @@ class CustomDevicesAddCommand extends CustomDevicesCommandBase { config: config, logger: logger, processManager: _processManager, - useImplicitPubspecResolution: globalResults!.flag(FlutterGlobalOptions.kImplicitPubspecResolution), ); bool result = true; diff --git a/packages/flutter_tools/lib/src/commands/daemon.dart b/packages/flutter_tools/lib/src/commands/daemon.dart index 88e8644dea8..3e90e59ac5a 100644 --- a/packages/flutter_tools/lib/src/commands/daemon.dart +++ b/packages/flutter_tools/lib/src/commands/daemon.dart @@ -32,7 +32,6 @@ import '../resident_runner.dart'; import '../run_cold.dart'; import '../run_hot.dart'; import '../runner/flutter_command.dart'; -import '../runner/flutter_command_runner.dart'; import '../vmservice.dart'; import '../web/web_runner.dart'; @@ -67,7 +66,6 @@ class DaemonCommand extends FlutterCommand { @override Future runCommand() async { - final bool useImplicitPubspecResolution = globalResults!.flag(FlutterGlobalOptions.kImplicitPubspecResolution); if (argResults!['listen-on-tcp-port'] != null) { int? port; try { @@ -84,7 +82,6 @@ class DaemonCommand extends FlutterCommand { outputPreferences: globals.outputPreferences, ), notifyingLogger: asLogger(globals.logger), - useImplicitPubspecResolution: useImplicitPubspecResolution, ).run(); return FlutterCommandResult.success(); } @@ -95,7 +92,6 @@ class DaemonCommand extends FlutterCommand { logger: globals.logger, ), notifyingLogger: asLogger(globals.logger), - useImplicitPubspecResolution: useImplicitPubspecResolution, ); final int code = await daemon.onExit; if (code != 0) { @@ -109,11 +105,10 @@ class DaemonCommand extends FlutterCommand { class DaemonServer { DaemonServer({ this.port, - required bool useImplicitPubspecResolution, required this.logger, this.notifyingLogger, @visibleForTesting Future Function(InternetAddress address, int port) bind = ServerSocket.bind, - }) : _bind = bind, _useImplicitPubspecResolution = useImplicitPubspecResolution; + }) : _bind = bind; final int? port; @@ -122,7 +117,6 @@ class DaemonServer { // Logger that sends the message to the other end of daemon connection. final NotifyingLogger? notifyingLogger; - final bool _useImplicitPubspecResolution; final Future Function(InternetAddress address, int port) _bind; @@ -157,7 +151,6 @@ class DaemonServer { logger: logger, ), notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: _useImplicitPubspecResolution, ); await daemon.onExit; await socketDone; @@ -176,14 +169,13 @@ typedef CommandHandlerWithBinary = Future Function(Map class Daemon { Daemon( this.connection, { - required bool useImplicitPubspecResolution, this.notifyingLogger, this.logToStdout = false, FileTransfer fileTransfer = const FileTransfer(), }) { // Set up domains. registerDomain(daemonDomain = DaemonDomain(this)); - registerDomain(appDomain = AppDomain(this, useImplicitPubspecResolution: useImplicitPubspecResolution)); + registerDomain(appDomain = AppDomain(this)); registerDomain(deviceDomain = DeviceDomain(this)); registerDomain(emulatorDomain = EmulatorDomain(this)); registerDomain(devToolsDomain = DevToolsDomain(this)); @@ -645,10 +637,7 @@ typedef RunOrAttach = Future Function({ /// /// It fires events for application start, stop, and stdout and stderr. class AppDomain extends Domain { - AppDomain(Daemon daemon, { - required bool useImplicitPubspecResolution, - }) : _useImplicitPubspecResolution = useImplicitPubspecResolution, - super(daemon, 'app') { + AppDomain(Daemon daemon) : super(daemon, 'app') { registerHandler('restart', restart); registerHandler('callServiceExtension', callServiceExtension); registerHandler('stop', stop); @@ -660,7 +649,6 @@ class AppDomain extends Domain { static String _getNewAppId() => _uuidGenerator.v4(); final List _apps = []; - final bool _useImplicitPubspecResolution; final DebounceOperationQueue operationQueue = DebounceOperationQueue(); @@ -679,7 +667,6 @@ class AppDomain extends Domain { String? isolateFilter, bool machine = true, String? userIdentifier, - required HotRunnerNativeAssetsBuilder? nativeAssetsBuilder, }) async { if (!await device.supportsRuntimeMode(options.buildInfo.mode)) { throw Exception( @@ -717,7 +704,6 @@ class AppDomain extends Domain { systemClock: globals.systemClock, logger: globals.logger, fileSystem: globals.fs, - useImplicitPubspecResolution: _useImplicitPubspecResolution, ); } else if (enableHotReload) { runner = HotRunner( @@ -730,8 +716,6 @@ class AppDomain extends Domain { hostIsIde: true, machine: machine, analytics: globals.analytics, - nativeAssetsBuilder: nativeAssetsBuilder, - useImplicitPubspecResolution: _useImplicitPubspecResolution, ); } else { runner = ColdRunner( @@ -740,7 +724,6 @@ class AppDomain extends Domain { debuggingOptions: options, applicationBinary: applicationBinary, machine: machine, - useImplicitPubspecResolution: _useImplicitPubspecResolution, ); } @@ -917,7 +900,7 @@ class AppDomain extends Domain { if (app == null) { throw DaemonException("app '$appId' not found"); } - final FlutterDevice device = app.runner!.flutterDevices.first; + final FlutterDevice device = app.runner.flutterDevices.first; final List views = await device.vmService!.getFlutterViews(); final Map? result = await device .vmService! @@ -1565,20 +1548,24 @@ class NotifyingLogger extends DelegatingLogger { /// A running application, started by this daemon. class AppInstance { - AppInstance(this.id, { this.runner, this.logToStdout = false, required AppRunLogger logger }) - : _logger = logger; + AppInstance( + this.id, { + required this.runner, + this.logToStdout = false, + required AppRunLogger logger, + }) : _logger = logger; final String id; - final ResidentRunner? runner; + final ResidentRunner runner; final bool logToStdout; final AppRunLogger _logger; Future restart({ bool fullRestart = false, bool pause = false, String? reason }) { - return runner!.restart(fullRestart: fullRestart, pause: pause, reason: reason); + return runner.restart(fullRestart: fullRestart, pause: pause, reason: reason); } - Future stop() => runner!.exit(); - Future detach() => runner!.detach(); + Future stop() => runner.exit(); + Future detach() => runner.detach(); void closeLogger() { _logger.close(); diff --git a/packages/flutter_tools/lib/src/commands/drive.dart b/packages/flutter_tools/lib/src/commands/drive.dart index 85ce947c6dc..4921ccc4285 100644 --- a/packages/flutter_tools/lib/src/commands/drive.dart +++ b/packages/flutter_tools/lib/src/commands/drive.dart @@ -28,7 +28,6 @@ import '../ios/devices.dart'; import '../macos/macos_ipad_device.dart'; import '../resident_runner.dart'; import '../runner/flutter_command.dart' show FlutterCommandCategory, FlutterCommandResult, FlutterOptions; -import '../runner/flutter_command_runner.dart'; import '../web/web_device.dart'; import 'run.dart'; @@ -261,7 +260,6 @@ class DriveCommand extends RunCommandBase { processUtils: globals.processUtils, dartSdkPath: globals.artifacts!.getArtifactPath(Artifact.engineDartBinary), devtoolsLauncher: DevtoolsLauncher.instance!, - useImplicitPubspecResolution: globalResults!.flag(FlutterGlobalOptions.kImplicitPubspecResolution), ); final File packageConfigFile = findPackageConfigFileOrDefault(_fileSystem.currentDirectory); diff --git a/packages/flutter_tools/lib/src/commands/packages.dart b/packages/flutter_tools/lib/src/commands/packages.dart index 211ce5e12cd..9ef6a478088 100644 --- a/packages/flutter_tools/lib/src/commands/packages.dart +++ b/packages/flutter_tools/lib/src/commands/packages.dart @@ -21,7 +21,6 @@ import '../plugins.dart'; import '../project.dart'; import '../reporting/reporting.dart'; import '../runner/flutter_command.dart'; -import '../runner/flutter_command_runner.dart'; /// The function signature of the [print] function. typedef PrintFn = void Function(Object?); @@ -305,7 +304,6 @@ class PackagesGetCommand extends FlutterCommand { projectDir: rootProject.directory, packageConfigPath: packageConfigPath(), generateDartPluginRegistry: true, - useImplicitPubspecResolution: globalResults!.flag(FlutterGlobalOptions.kImplicitPubspecResolution), ); await generateLocalizationsSyntheticPackage( @@ -329,7 +327,6 @@ class PackagesGetCommand extends FlutterCommand { projectDir: rootProject.directory, packageConfigPath: packageConfigPath(), generateDartPluginRegistry: true, - useImplicitPubspecResolution: globalResults!.flag(FlutterGlobalOptions.kImplicitPubspecResolution), ); final BuildResult result = await globals.buildSystem.build( const GenerateLocalizationsTarget(), @@ -386,15 +383,10 @@ class PackagesGetCommand extends FlutterCommand { if (rootProject != null) { // We need to regenerate the platform specific tooling for both the project // itself and example(if present). - final bool useImplicitPubspecResolution = boolArg(FlutterGlobalOptions.kImplicitPubspecResolution, global: true); - await rootProject.regeneratePlatformSpecificTooling( - useImplicitPubspecResolution: useImplicitPubspecResolution, - ); + await rootProject.regeneratePlatformSpecificTooling(); if (example && rootProject.hasExampleApp && rootProject.example.pubspecFile.existsSync()) { final FlutterProject exampleProject = rootProject.example; - await exampleProject.regeneratePlatformSpecificTooling( - useImplicitPubspecResolution: useImplicitPubspecResolution, - ); + await exampleProject.regeneratePlatformSpecificTooling(); } } @@ -407,7 +399,7 @@ class PackagesGetCommand extends FlutterCommand { return []; } - return findPlugins(rootProject, throwOnError: false, useImplicitPubspecResolution: boolArg(FlutterGlobalOptions.kImplicitPubspecResolution, global: true)); + return findPlugins(rootProject, throwOnError: false); })(); late final String? _androidEmbeddingVersion = _rootProject?.android.getEmbeddingVersion().toString().split('.').last; diff --git a/packages/flutter_tools/lib/src/commands/run.dart b/packages/flutter_tools/lib/src/commands/run.dart index 10fbe0914e0..48bb8fa9148 100644 --- a/packages/flutter_tools/lib/src/commands/run.dart +++ b/packages/flutter_tools/lib/src/commands/run.dart @@ -28,7 +28,6 @@ import '../run_hot.dart'; import '../runner/flutter_command.dart'; import '../runner/flutter_command_runner.dart'; import '../tracing.dart'; -import '../vmservice.dart'; import '../web/compile.dart'; import '../web/web_constants.dart'; import '../web/web_runner.dart'; @@ -40,7 +39,6 @@ abstract class RunCommandBase extends FlutterCommand with DeviceBasedDevelopment addBuildModeFlags(verboseHelp: verboseHelp, defaultToRelease: false); usesDartDefineOption(); usesFlavorOption(); - usesWebRendererOption(); usesWebResourcesCdnFlag(); addNativeNullAssertions(hide: !verboseHelp); addBundleSkSLPathOption(hide: !verboseHelp); @@ -235,10 +233,13 @@ abstract class RunCommandBase extends FlutterCommand with DeviceBasedDevelopment bool get useWasm => boolArg(FlutterOptions.kWebWasmFlag); - WebRendererMode get webRenderer => WebRendererMode.fromCliOption( - stringArg(FlutterOptions.kWebRendererFlag), - useWasm: useWasm - ); + // Keep in sync with the [TestCommand.webRenderer] getter. + WebRendererMode get webRenderer { + final List dartDefines = extractDartDefines( + defineConfigJsonMap: extractDartDefineConfigJsonMap() + ); + return WebRendererMode.fromDartDefines(dartDefines, useWasm: useWasm); + } /// Create a debugging options instance for the current `run` or `drive` invocation. @visibleForTesting @@ -350,9 +351,7 @@ abstract class RunCommandBase extends FlutterCommand with DeviceBasedDevelopment class RunCommand extends RunCommandBase { RunCommand({ bool verboseHelp = false, - HotRunnerNativeAssetsBuilder? nativeAssetsBuilder, - }) : _nativeAssetsBuilder = nativeAssetsBuilder, - super(verboseHelp: verboseHelp) { + }) : super(verboseHelp: verboseHelp) { requiresPubspecYaml(); usesFilesystemOptions(hide: !verboseHelp); usesExtraDartFlagOptions(verboseHelp: verboseHelp); @@ -436,8 +435,6 @@ class RunCommand extends RunCommandBase { ); } - final HotRunnerNativeAssetsBuilder? _nativeAssetsBuilder; - @override final String name = 'run'; @@ -682,7 +679,6 @@ class RunCommand extends RunCommandBase { required String? applicationBinaryPath, required FlutterProject flutterProject, }) async { - final bool useImplicitPubspecResolution = globalResults!.flag(FlutterGlobalOptions.kImplicitPubspecResolution); if (hotMode && !webMode) { return HotRunner( flutterDevices, @@ -697,8 +693,6 @@ class RunCommand extends RunCommandBase { stayResident: stayResident, analytics: globals.analytics, nativeAssetsYamlFile: stringArg(FlutterOptions.kNativeAssetsYamlFile), - nativeAssetsBuilder: _nativeAssetsBuilder, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); } else if (webMode) { return webRunnerFactory!.createWebRunner( @@ -712,7 +706,6 @@ class RunCommand extends RunCommandBase { analytics: globals.analytics, logger: globals.logger, systemClock: globals.systemClock, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); } return ColdRunner( @@ -725,13 +718,11 @@ class RunCommand extends RunCommandBase { ? null : globals.fs.file(applicationBinaryPath), stayResident: stayResident, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); } @visibleForTesting Daemon createMachineDaemon() { - final bool useImplicitPubspecResolution = globalResults!.flag(FlutterGlobalOptions.kImplicitPubspecResolution); final Daemon daemon = Daemon( DaemonConnection( daemonStreams: DaemonStreams.fromStdio(globals.stdio, logger: globals.logger), @@ -741,7 +732,6 @@ class RunCommand extends RunCommandBase { ? globals.logger as NotifyingLogger : NotifyingLogger(verbose: globals.logger.isVerbose, parent: globals.logger), logToStdout: true, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); return daemon; } @@ -772,13 +762,12 @@ class RunCommand extends RunCommandBase { packagesFilePath: globalResults![FlutterGlobalOptions.kPackagesOption] as String?, dillOutputPath: stringArg('output-dill'), userIdentifier: userIdentifier, - nativeAssetsBuilder: _nativeAssetsBuilder, ); } on Exception catch (error) { throwToolExit(error.toString()); } final DateTime appStartedTime = globals.systemClock.now(); - final int result = await app.runner!.waitForAppToFinish(); + final int result = await app.runner.waitForAppToFinish(); if (result != 0) { throwToolExit(null, exitCode: result); } @@ -866,7 +855,7 @@ class RunCommand extends RunCommandBase { throwToolExit(null, exitCode: result); } } on RPCError catch (error) { - if (error.code == RPCErrorCodes.kServiceDisappeared || + if (error.code == RPCErrorKind.kServiceDisappeared.code || error.message.contains('Service connection disposed')) { throwToolExit('Lost connection to device.'); } diff --git a/packages/flutter_tools/lib/src/commands/test.dart b/packages/flutter_tools/lib/src/commands/test.dart index 0183f843bbf..ded767a9d8c 100644 --- a/packages/flutter_tools/lib/src/commands/test.dart +++ b/packages/flutter_tools/lib/src/commands/test.dart @@ -76,7 +76,6 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts { usesTrackWidgetCreation(verboseHelp: verboseHelp); addEnableExperimentation(hide: !verboseHelp); usesDartDefineOption(); - usesWebRendererOption(); usesDeviceUserOption(); usesFlavorOption(); addEnableImpellerFlag(verboseHelp: verboseHelp); @@ -336,10 +335,13 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts { return super.verifyThenRunCommand(commandPath); } - WebRendererMode get webRenderer => WebRendererMode.fromCliOption( - stringArg(FlutterOptions.kWebRendererFlag), - useWasm: useWasm - ); + // Keep in sync with the [RunCommandBase.webRenderer] getter. + WebRendererMode get webRenderer { + final List dartDefines = extractDartDefines( + defineConfigJsonMap: extractDartDefineConfigJsonMap() + ); + return WebRendererMode.fromDartDefines(dartDefines, useWasm: useWasm); + } @override Future runCommand() async { @@ -419,7 +421,8 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts { webUseWasm: useWasm, ); - String? testAssetDirectory; + final Uri? nativeAssetsJson = await nativeAssetsBuilder?.build(buildInfo); + String? testAssetPath; if (buildTestAssets) { await _buildTestAsset( flavor: buildInfo.flavor, @@ -427,8 +430,19 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts { buildMode: debuggingOptions.buildInfo.mode, packageConfigPath: buildInfo.packageConfigPath, ); - testAssetDirectory = globals.fs.path. - join(flutterProject.directory.path, 'build', 'unit_test_assets'); + } + if (buildTestAssets || nativeAssetsJson != null) { + testAssetPath = globals.fs.path + .join(flutterProject.directory.path, 'build', 'unit_test_assets'); + } + if (nativeAssetsJson != null) { + final Directory testAssetDirectory = globals.fs.directory(testAssetPath); + if (!testAssetDirectory.existsSync()) { + await testAssetDirectory.create(recursive: true); + } + final File nativeAssetsManifest = + testAssetDirectory.childFile('NativeAssetsManifest.json'); + await globals.fs.file(nativeAssetsJson).copy(nativeAssetsManifest.path); } final String? concurrencyString = stringArg('concurrency'); @@ -585,7 +599,7 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts { machine: machine, updateGoldens: boolArg('update-goldens'), concurrency: jobs, - testAssetDirectory: testAssetDirectory, + testAssetDirectory: testAssetPath, flutterProject: flutterProject, randomSeed: stringArg('test-randomize-ordering-seed'), reporter: stringArg('reporter'), @@ -612,7 +626,7 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts { machine: machine, updateGoldens: boolArg('update-goldens'), concurrency: jobs, - testAssetDirectory: testAssetDirectory, + testAssetDirectory: testAssetPath, flutterProject: flutterProject, web: isWeb, randomSeed: stringArg('test-randomize-ordering-seed'), diff --git a/packages/flutter_tools/lib/src/commands/update_packages.dart b/packages/flutter_tools/lib/src/commands/update_packages.dart index 0dc01d58cae..0b6289cdacc 100644 --- a/packages/flutter_tools/lib/src/commands/update_packages.dart +++ b/packages/flutter_tools/lib/src/commands/update_packages.dart @@ -1741,7 +1741,7 @@ Directory createTemporaryFlutterSdk( // Fill in SDK dependency constraint. output.write(''' environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 '''); output.writeln('dependencies:'); @@ -1773,7 +1773,7 @@ description: Dart SDK extensions for dart:ui homepage: http://flutter.io # sky_engine requires sdk_ext support in the analyzer which was added in 1.11.x environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 '''); return directory; diff --git a/packages/flutter_tools/lib/src/commands/widget_preview.dart b/packages/flutter_tools/lib/src/commands/widget_preview.dart new file mode 100644 index 00000000000..8cc9d9c6892 --- /dev/null +++ b/packages/flutter_tools/lib/src/commands/widget_preview.dart @@ -0,0 +1,321 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:args/args.dart'; +import 'package:meta/meta.dart'; + +import '../base/common.dart'; +import '../base/deferred_component.dart'; +import '../base/file_system.dart'; +import '../base/platform.dart'; +import '../cache.dart'; +import '../convert.dart'; +import '../dart/pub.dart'; +import '../flutter_manifest.dart'; + +import '../globals.dart' as globals; +import '../project.dart'; +import '../runner/flutter_command.dart'; +import 'create_base.dart'; + +class WidgetPreviewCommand extends FlutterCommand { + WidgetPreviewCommand() { + addSubcommand(WidgetPreviewStartCommand()); + addSubcommand(WidgetPreviewCleanCommand()); + } + + @override + String get description => 'Manage the widget preview environment.'; + + @override + String get name => 'widget-preview'; + + @override + String get category => FlutterCommandCategory.tools; + + // TODO(bkonyi): show when --verbose is not provided when this feature is + // ready to ship. + @override + bool get hidden => true; + + @override + Future runCommand() async => + FlutterCommandResult.fail(); +} + +/// Common utilities for the 'start' and 'clean' commands. +mixin WidgetPreviewSubCommandMixin on FlutterCommand { + FlutterProject getRootProject() { + final ArgResults results = argResults!; + final Directory projectDir; + if (results.rest case [final String directory]) { + projectDir = globals.fs.directory(directory); + if (!projectDir.existsSync()) { + throwToolExit('Could not find ${projectDir.path}.'); + } + } else if (results.rest.length > 1) { + throwToolExit('Only one directory should be provided.'); + } else { + projectDir = globals.fs.currentDirectory; + } + return validateFlutterProjectForPreview(projectDir); + } + + FlutterProject validateFlutterProjectForPreview(Directory directory) { + globals.logger + .printTrace('Verifying that ${directory.path} is a Flutter project.'); + final FlutterProject flutterProject = + globals.projectFactory.fromDirectory(directory); + if (!flutterProject.dartTool.existsSync()) { + throwToolExit( + '${flutterProject.directory.path} is not a valid Flutter project.', + ); + } + return flutterProject; + } +} + +class WidgetPreviewStartCommand extends FlutterCommand + with CreateBase, WidgetPreviewSubCommandMixin { + WidgetPreviewStartCommand() { + addPubOptions(); + } + + @override + String get description => 'Starts the widget preview environment.'; + + @override + String get name => 'start'; + + @override + Future runCommand() async { + final FlutterProject rootProject = getRootProject(); + final Directory widgetPreviewScaffold = rootProject.widgetPreviewScaffold; + + // Check to see if a preview scaffold has already been generated. If not, + // generate one. + if (!widgetPreviewScaffold.existsSync()) { + globals.logger.printStatus( + 'Creating widget preview scaffolding at: ${widgetPreviewScaffold.path}', + ); + await generateApp( + ['widget_preview_scaffold'], + widgetPreviewScaffold, + createTemplateContext( + organization: 'flutter', + projectName: 'widget_preview_scaffold', + titleCaseProjectName: 'Widget Preview Scaffold', + flutterRoot: Cache.flutterRoot!, + dartSdkVersionBounds: '^${globals.cache.dartSdkBuild}', + linux: const LocalPlatform().isLinux, + macos: const LocalPlatform().isMacOS, + windows: const LocalPlatform().isWindows, + ), + overwrite: true, + generateMetadata: false, + ); + await _populatePreviewPubspec(rootProject: rootProject); + } + return FlutterCommandResult.success(); + } + + @visibleForTesting + static const Map flutterGenPackageConfigEntry = + { + 'name': 'flutter_gen', + 'rootUri': '../../flutter_gen', + 'languageVersion': '2.12', + }; + + /// Maps asset URIs to relative paths for the widget preview project to + /// include. + @visibleForTesting + static Uri transformAssetUri(Uri uri) { + // Assets provided by packages always start with 'packages' and do not + // require their URIs to be updated. + if (uri.path.startsWith('packages')) { + return uri; + } + // Otherwise, the asset is contained within the root project and needs + // to be referenced from the widget preview scaffold project's pubspec. + return Uri(path: '../../${uri.path}'); + } + + @visibleForTesting + static AssetsEntry transformAssetsEntry(AssetsEntry asset) { + return AssetsEntry( + uri: transformAssetUri(asset.uri), + flavors: asset.flavors, + transformers: asset.transformers, + ); + } + + @visibleForTesting + static FontAsset transformFontAsset(FontAsset asset) { + return FontAsset( + transformAssetUri(asset.assetUri), + weight: asset.weight, + style: asset.style, + ); + } + + @visibleForTesting + static DeferredComponent transformDeferredComponent( + DeferredComponent component) { + return DeferredComponent( + name: component.name, + // TODO(bkonyi): verify these library paths are always package: paths from the parent project. + libraries: component.libraries, + assets: component.assets.map(transformAssetsEntry).toList(), + ); + } + + @visibleForTesting + FlutterManifest buildPubspec({ + required FlutterManifest rootManifest, + required FlutterManifest widgetPreviewManifest, + }) { + final List assets = + rootManifest.assets.map(transformAssetsEntry).toList(); + + final List fonts = rootManifest.fonts.map( + (Font font) { + return Font( + font.familyName, + font.fontAssets.map(transformFontAsset).toList(), + ); + }, + ).toList(); + + final List shaders = + rootManifest.shaders.map(transformAssetUri).toList(); + + final List models = + rootManifest.models.map(transformAssetUri).toList(); + + final List? deferredComponents = rootManifest + .deferredComponents + ?.map(transformDeferredComponent) + .toList(); + + return widgetPreviewManifest.copyWith( + logger: globals.logger, + assets: assets, + fonts: fonts, + shaders: shaders, + models: models, + deferredComponents: deferredComponents, + ); + } + + Future _populatePreviewPubspec({ + required FlutterProject rootProject, + }) async { + final FlutterProject widgetPreviewScaffoldProject = + rootProject.widgetPreviewScaffoldProject; + + // Overwrite the pubspec for the preview scaffold project to include assets + // from the root project. + widgetPreviewScaffoldProject.replacePubspec( + buildPubspec( + rootManifest: rootProject.manifest, + widgetPreviewManifest: widgetPreviewScaffoldProject.manifest, + ), + ); + + // Adds a path dependency on the parent project so previews can be + // imported directly into the preview scaffold. + const String pubAdd = 'add'; + await pub.interactively( + [ + pubAdd, + '--directory', + widgetPreviewScaffoldProject.directory.path, + '${rootProject.manifest.appName}:{"path":${rootProject.directory.path}}', + ], + context: PubContext.pubAdd, + command: pubAdd, + touchesPackageConfig: true, + ); + + // Generate package_config.json. + await pub.get( + context: PubContext.create, + project: widgetPreviewScaffoldProject, + offline: offline, + outputMode: PubOutputMode.summaryOnly, + ); + + if (rootProject.manifest.generateSyntheticPackage) { + maybeAddFlutterGenToPackageConfig( + rootProject: rootProject, + ); + } + } + + /// Manually adds an entry for package:flutter_gen to the preview scaffold's + /// package_config.json if the target project makes use of localization. + /// + /// The Flutter Tool does this when running a Flutter project with + /// localization instead of modifying the user's pubspec.yaml to depend on it + /// as a path dependency. Unfortunately, the preview scaffold still needs to + /// add it directly to its package_config.json as the generated package name + /// isn't actually flutter_gen, which pub doesn't really like, and using the + /// actual package name will break applications which import + /// package:flutter_gen. + void maybeAddFlutterGenToPackageConfig({ + required FlutterProject rootProject, + }) { + if (!rootProject.manifest.generateSyntheticPackage) { + return; + } + final FlutterProject widgetPreviewScaffoldProject = + rootProject.widgetPreviewScaffoldProject; + final File packageConfig = widgetPreviewScaffoldProject.packageConfig; + final String previewPackageConfigPath = packageConfig.path; + if (!packageConfig.existsSync()) { + throw StateError( + "Could not find preview project's package_config.json at " + '$previewPackageConfigPath', + ); + } + final Map packageConfigJson = json.decode( + packageConfig.readAsStringSync(), + ) as Map; + (packageConfigJson['packages'] as List?)! + .cast>() + .add(flutterGenPackageConfigEntry); + packageConfig.writeAsStringSync( + json.encode(packageConfigJson), + ); + globals.logger.printStatus( + 'Added flutter_gen dependency to $previewPackageConfigPath', + ); + } +} + +class WidgetPreviewCleanCommand extends FlutterCommand + with WidgetPreviewSubCommandMixin { + @override + String get description => 'Cleans up widget preview state.'; + + @override + String get name => 'clean'; + + @override + Future runCommand() async { + final Directory widgetPreviewScaffold = + getRootProject().widgetPreviewScaffold; + if (widgetPreviewScaffold.existsSync()) { + final String scaffoldPath = widgetPreviewScaffold.path; + globals.logger.printStatus( + 'Deleting widget preview scaffold at $scaffoldPath.', + ); + widgetPreviewScaffold.deleteSync(recursive: true); + } else { + globals.logger.printStatus('Nothing to clean up.'); + } + return FlutterCommandResult.success(); + } +} diff --git a/packages/flutter_tools/lib/src/compile.dart b/packages/flutter_tools/lib/src/compile.dart index a317f447986..eb4fc73620f 100644 --- a/packages/flutter_tools/lib/src/compile.dart +++ b/packages/flutter_tools/lib/src/compile.dart @@ -61,7 +61,7 @@ class TargetModel { } class CompilerOutput { - const CompilerOutput(this.outputFilename, this.errorCount, this.sources, {this.expressionData}); + const CompilerOutput(this.outputFilename, this.errorCount, this.sources, {this.expressionData, this.errorMessage}); final String outputFilename; final int errorCount; @@ -69,6 +69,9 @@ class CompilerOutput { /// This field is only non-null for expression compilation requests. final Uint8List? expressionData; + + /// This field is only non-null when a compilation error was encountered. + final String? errorMessage; } enum StdoutState { CollectDiagnostic, CollectDependencies } @@ -94,6 +97,7 @@ class StdoutHandler { bool _suppressCompilerMessages = false; bool _expectSources = true; bool _readFile = false; + StringBuffer _errorBuffer = StringBuffer(); void handler(String message) { const String kResultPrefix = 'result '; @@ -125,6 +129,7 @@ class StdoutHandler { errorCount, sources, expressionData: expressionData, + errorMessage: _errorBuffer.isNotEmpty ? _errorBuffer.toString() : null, ); compilerOutput?.complete(output); return; @@ -132,8 +137,10 @@ class StdoutHandler { switch (state) { case StdoutState.CollectDiagnostic when _suppressCompilerMessages: _logger.printTrace(message); + _errorBuffer.writeln(message); case StdoutState.CollectDiagnostic: _logger.printError(message); + _errorBuffer.writeln(message); case StdoutState.CollectDependencies: switch (message[0]) { case '+': @@ -155,6 +162,7 @@ class StdoutHandler { _expectSources = expectSources; _readFile = readFile; state = StdoutState.CollectDiagnostic; + _errorBuffer = StringBuffer(); } } diff --git a/packages/flutter_tools/lib/src/compute_dev_dependencies.dart b/packages/flutter_tools/lib/src/compute_dev_dependencies.dart index 7c76b855c54..a2bfcb8507d 100644 --- a/packages/flutter_tools/lib/src/compute_dev_dependencies.dart +++ b/packages/flutter_tools/lib/src/compute_dev_dependencies.dart @@ -2,11 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:process/process.dart'; - -import 'base/io.dart'; import 'base/logger.dart'; import 'convert.dart'; +import 'dart/pub.dart'; +import 'project.dart'; /// Returns dependencies of [project] that are _only_ used as `dev_dependency`. /// @@ -15,55 +14,24 @@ import 'convert.dart'; /// `pubspec.yaml` file, and removing packages from that set that appear as /// dependencies (implicitly non-dev) in any non-dev package depended on. Future> computeExclusiveDevDependencies( - ProcessManager processes, { + Pub pub, { required Logger logger, - required String projectPath, + required FlutterProject project, }) async { - final ProcessResult processResult = await processes.run( - ['dart', 'pub', 'deps', '--json'], - workingDirectory: projectPath, - ); + final Map jsonResult = await pub.deps(project); Never fail([String? reason]) { - final Object? stdout = processResult.stdout; - if (stdout is String && stdout.isNotEmpty) { - logger.printTrace(stdout); - } - final String stderr = processResult.stderr.toString(); + logger.printTrace(const JsonEncoder.withIndent(' ').convert(jsonResult)); throw StateError( 'dart pub deps --json ${reason != null ? 'had unexpected output: $reason' : 'failed'}' - '${stderr.isNotEmpty ? '\n$stderr' : ''}', ); } - // Guard against dart pub deps crashing. - final Map jsonResult; - if (processResult.exitCode != 0 || processResult.stdout is! String) { - fail(); - } - - // Guard against dart pub deps having explicitly invalid output. - final String stdout; - try { - stdout = processResult.stdout as String; - - // This is an indication that `FakeProcessManager.any` was used, which by - // contract emits exit code 0 and no output on either stdout or stderr. To - // avoid this code, we'd have to go and make this function injectable into - // every callsite and mock-it out manually, which at the time of this - // writing was 130+ unit test cases alone. - // - // So, this is the lesser of two evils. - if (stdout.isEmpty && processResult.stderr == '') { - return {}; - } - - jsonResult = json.decode(stdout) as Map; - } on FormatException catch (e) { - fail('$e'); - } - List asListOrFail(Object? value, String name) { + // Allow omitting a list as empty to default to an empty list + if (value == null) { + return []; + } if (value is! List) { fail('Expected field "$name" to be a list, got "$value"'); } @@ -115,7 +83,7 @@ Future> computeExclusiveDevDependencies( // Start initially with every `devDependency` listed. final Set devDependencies = asListOrFail( - rootPackage['devDependencies'], + rootPackage['devDependencies'] ?? [], 'devDependencies', ).toSet(); @@ -149,7 +117,7 @@ Future> computeExclusiveDevDependencies( // Remove any listed dependency from dev dependencies; it might have been // a dev dependency for the app (root) package, but it is being used as a - // real dependency for a dependend on package, so we would not want to send + // real dependency for a dependent on package, so we would not want to send // a signal that the package can be ignored/removed. devDependencies.removeAll(directDependencies); diff --git a/packages/flutter_tools/lib/src/context_runner.dart b/packages/flutter_tools/lib/src/context_runner.dart index cd6755d8509..f01c56fc59c 100644 --- a/packages/flutter_tools/lib/src/context_runner.dart +++ b/packages/flutter_tools/lib/src/context_runner.dart @@ -68,7 +68,6 @@ import 'windows/windows_workflow.dart'; Future runInContext( FutureOr Function() runner, { - bool useImplicitPubspecResolution = true, Map? overrides, }) async { @@ -211,7 +210,6 @@ Future runInContext( operatingSystemUtils: globals.os, customDevicesConfig: globals.customDevicesConfig, nativeAssetsBuilder: globals.nativeAssetsBuilder, - useImplicitPubspecResolution: useImplicitPubspecResolution, ), DevtoolsLauncher: () => DevtoolsServerLauncher( processManager: globals.processManager, diff --git a/packages/flutter_tools/lib/src/custom_devices/custom_device.dart b/packages/flutter_tools/lib/src/custom_devices/custom_device.dart index a6ba1952450..c5f7745a4fd 100644 --- a/packages/flutter_tools/lib/src/custom_devices/custom_device.dart +++ b/packages/flutter_tools/lib/src/custom_devices/custom_device.dart @@ -23,6 +23,7 @@ import '../device_port_forwarder.dart'; import '../features.dart'; import '../project.dart'; import '../protocol_discovery.dart'; +import '../vmservice.dart'; import 'custom_device_config.dart'; import 'custom_device_workflow.dart'; import 'custom_devices_config.dart'; @@ -111,6 +112,9 @@ class CustomDeviceLogReader extends DeviceLogReader { @override Stream get logLines => logLinesController.stream; + + @override + Future provideVmService(FlutterVmService connectedVmService) async { } } /// A [DevicePortForwarder] that uses commands to forward / unforward a port. @@ -440,10 +444,8 @@ class CustomDevice extends Device { required CustomDeviceConfig config, required super.logger, required ProcessManager processManager, - required bool useImplicitPubspecResolution, }) : _config = config, _logger = logger, - _useImplicitPubspecResolution = useImplicitPubspecResolution, _processManager = processManager, _processUtils = ProcessUtils( processManager: processManager, @@ -471,7 +473,6 @@ class CustomDevice extends Device { final ProcessUtils _processUtils; final Map _sessions = {}; final CustomDeviceLogReader _globalLogReader; - final bool _useImplicitPubspecResolution; @override final DevicePortForwarder portForwarder; @@ -765,7 +766,6 @@ class CustomDevice extends Device { mainPath: mainPath, depfilePath: defaultDepfilePath, assetDirPath: assetBundleDir, - useImplicitPubspecResolution: _useImplicitPubspecResolution, ); // if we have a post build step (needed for some embedders), execute it @@ -827,17 +827,14 @@ class CustomDevices extends PollingDeviceDiscovery { required ProcessManager processManager, required Logger logger, required CustomDevicesConfig config, - required bool useImplicitPubspecResolution, }) : _customDeviceWorkflow = CustomDeviceWorkflow( featureFlags: featureFlags, ), - _useImplicitPubspecResolution = useImplicitPubspecResolution, _logger = logger, _processManager = processManager, _config = config, super('custom devices'); - final bool _useImplicitPubspecResolution; final CustomDeviceWorkflow _customDeviceWorkflow; final ProcessManager _processManager; final Logger _logger; @@ -859,7 +856,6 @@ class CustomDevices extends PollingDeviceDiscovery { config: config, logger: _logger, processManager: _processManager, - useImplicitPubspecResolution: _useImplicitPubspecResolution, ) ).toList(); } diff --git a/packages/flutter_tools/lib/src/dart/generate_synthetic_packages.dart b/packages/flutter_tools/lib/src/dart/generate_synthetic_packages.dart index b5c0e6f1339..fd96d0b82a3 100644 --- a/packages/flutter_tools/lib/src/dart/generate_synthetic_packages.dart +++ b/packages/flutter_tools/lib/src/dart/generate_synthetic_packages.dart @@ -9,6 +9,7 @@ import '../base/file_system.dart'; import '../base/utils.dart'; import '../build_system/build_system.dart'; import '../build_system/build_targets.dart'; +import '../features.dart'; Future generateLocalizationsSyntheticPackage({ required Environment environment, @@ -51,19 +52,19 @@ Future generateLocalizationsSyntheticPackage({ if (isSyntheticL10nPackage == false) { return; } - } else if (!environment.useImplicitPubspecResolution) { - // --no-implicit-pubspec-resolution was passed, and synthetic-packages: true was not. + } else if (featureFlags.isExplicitPackageDependenciesEnabled) { + // synthetic-packages: true was not set and it is no longer the default. return; } - if (!environment.useImplicitPubspecResolution) { + if (featureFlags.isExplicitPackageDependenciesEnabled) { throwToolExit( - 'Cannot generate a synthetic package when --no-implicit-pubspec-resolution is passed.\n' + 'Cannot generate a synthetic package when explicit-package-dependencies is enabled.\n' '\n' 'Synthetic package output (package:flutter_gen) is deprecated: ' 'https://flutter.dev/to/flutter-gen-deprecation. If you are seeing this ' - 'message either you have provided --no-implicit-pubspec-resolution, or ' - 'it is the default value (see flutter --verbose --help).', + 'message either you have provided explicit-package-dependencies, or it ' + 'is the default value (see flutter config --help).', ); } diff --git a/packages/flutter_tools/lib/src/dart/pub.dart b/packages/flutter_tools/lib/src/dart/pub.dart index 656ab79109d..605f90e8cf7 100644 --- a/packages/flutter_tools/lib/src/dart/pub.dart +++ b/packages/flutter_tools/lib/src/dart/pub.dart @@ -138,7 +138,7 @@ abstract class Pub { /// skipped if the package config file has a "generator" other than "pub". /// Defaults to true. /// - /// [outputMode] determines how verbose the output from `pub get` will be. + /// [outputMode] determines how detailed the output from `pub get` will be. /// If [PubOutputMode.all] is used, `pub get` will print its typical output /// which includes information about all changed dependencies. If /// [PubOutputMode.summaryOnly] is used, only summary information will be printed. @@ -157,6 +157,13 @@ abstract class Pub { PubOutputMode outputMode = PubOutputMode.all, }); + /// Runs, parses, and returns `pub deps --json` for [project]. + /// + /// While it is guaranteed that, if successful, that the result are a valid + /// JSON object, the exact contents returned are _not_ validated, and are left + /// as a responsibility of the caller. + Future> deps(FlutterProject project); + /// Runs pub in 'batch' mode. /// /// forwarding complete lines written by pub to its stdout/stderr streams to @@ -346,12 +353,9 @@ class _DefaultPub implements Pub { } final String command = upgrade ? 'upgrade' : 'get'; - final bool verbose = _logger.isVerbose; final List args = [ if (_logger.supportsColor) '--color', - if (verbose) - '--verbose', '--directory', _fileSystem.path.relative(directory), ...[ @@ -373,6 +377,48 @@ class _DefaultPub implements Pub { await _updateVersionAndPackageConfig(project); } + @override + Future> deps(FlutterProject project) async { + final List pubCommand = [ + ..._pubCommand, + 'deps', + '--json', + ]; + + final RunResult runResult = await _processUtils.run( + pubCommand, + workingDirectory: project.directory.path, + ); + + Never fail([String? reason]) { + final String stdout = runResult.stdout; + if (stdout.isNotEmpty) { + _logger.printTrace(stdout); + } + final String stderr = runResult.stderr; + throw StateError( + '${pubCommand.join(' ')} ${reason != null ? 'had unexpected output: $reason' : 'failed'}' + '${stderr.isNotEmpty ? '\n$stderr' : ''}', + ); + } + + // Guard against dart pub deps crashing. + if (runResult.exitCode != 0) { + fail(); + } + + // Guard against dart pub deps having explicitly invalid output. + try { + final Object? result = json.decode(runResult.stdout); + if (result is! Map) { + fail('Not a JSON object'); + } + return result; + } on FormatException catch (e) { + fail('$e'); + } + } + /// Runs pub with [arguments] and [ProcessStartMode.inheritStdio] mode. /// /// Uses [ProcessStartMode.normal] and [Pub._stdio] if [Pub.test] constructor diff --git a/packages/flutter_tools/lib/src/desktop_device.dart b/packages/flutter_tools/lib/src/desktop_device.dart index a7579bdd085..0ec5c5a907a 100644 --- a/packages/flutter_tools/lib/src/desktop_device.dart +++ b/packages/flutter_tools/lib/src/desktop_device.dart @@ -19,6 +19,7 @@ import 'device_port_forwarder.dart'; import 'globals.dart' as globals; import 'macos/macos_device.dart'; import 'protocol_discovery.dart'; +import 'vmservice.dart'; /// A partial implementation of Device for desktop-class devices to inherit /// from, containing implementations that are common to all desktop devices. @@ -384,4 +385,7 @@ class DesktopLogReader extends DeviceLogReader { void dispose() { // Nothing to dispose. } + + @override + Future provideVmService(FlutterVmService connectedVmService) async { } } diff --git a/packages/flutter_tools/lib/src/devfs.dart b/packages/flutter_tools/lib/src/devfs.dart index c42a19b0fc0..c5c6b216bb1 100644 --- a/packages/flutter_tools/lib/src/devfs.dart +++ b/packages/flutter_tools/lib/src/devfs.dart @@ -516,7 +516,7 @@ class DevFS { final vm_service.Response response = await _vmService.createDevFS(fsName); _baseUri = Uri.parse(response.json!['uri'] as String); } on vm_service.RPCError catch (rpcException) { - if (rpcException.code == RPCErrorCodes.kServiceDisappeared || + if (rpcException.code == vm_service.RPCErrorKind.kServiceDisappeared.code || rpcException.message.contains('Service connection disposed')) { // This can happen if the device has been disconnected, so translate to // a DevFSException, which the caller will handle. diff --git a/packages/flutter_tools/lib/src/device.dart b/packages/flutter_tools/lib/src/device.dart index fa198f535ad..da778aa5f07 100644 --- a/packages/flutter_tools/lib/src/device.dart +++ b/packages/flutter_tools/lib/src/device.dart @@ -1440,14 +1440,11 @@ abstract class DeviceLogReader { /// Some logs can be obtained from a VM service stream. /// Set this after the VM services are connected. - FlutterVmService? connectedVMService; + Future provideVmService(FlutterVmService connectedVmService); @override String toString() => name; - /// Process ID of the app on the device. - int? appPid; - // Clean up resources allocated by log reader e.g. subprocesses void dispose(); } @@ -1466,17 +1463,14 @@ class NoOpDeviceLogReader implements DeviceLogReader { @override final String name; - @override - int? appPid; - - @override - FlutterVmService? connectedVMService; - @override Stream get logLines => const Stream.empty(); @override void dispose() { } + + @override + Future provideVmService(FlutterVmService connectedVmService) async {} } /// Append --null_assertions to any existing Dart VM flags if diff --git a/packages/flutter_tools/lib/src/drive/drive_service.dart b/packages/flutter_tools/lib/src/drive/drive_service.dart index b260a031073..bb7473d0851 100644 --- a/packages/flutter_tools/lib/src/drive/drive_service.dart +++ b/packages/flutter_tools/lib/src/drive/drive_service.dart @@ -28,20 +28,17 @@ class FlutterDriverFactory { required ProcessUtils processUtils, required String dartSdkPath, required DevtoolsLauncher devtoolsLauncher, - required bool useImplicitPubspecResolution, }) : _applicationPackageFactory = applicationPackageFactory, _logger = logger, _processUtils = processUtils, _dartSdkPath = dartSdkPath, - _devtoolsLauncher = devtoolsLauncher, - _useImplicitPubspecResolution = useImplicitPubspecResolution; + _devtoolsLauncher = devtoolsLauncher; final ApplicationPackageFactory _applicationPackageFactory; final Logger _logger; final ProcessUtils _processUtils; final String _dartSdkPath; final DevtoolsLauncher _devtoolsLauncher; - final bool _useImplicitPubspecResolution; /// Create a driver service for running `flutter drive`. DriverService createDriverService(bool web) { @@ -50,7 +47,6 @@ class FlutterDriverFactory { logger: _logger, processUtils: _processUtils, dartSdkPath: _dartSdkPath, - useImplicitPubspecResolution: _useImplicitPubspecResolution, ); } return FlutterDriverService( @@ -235,9 +231,7 @@ class FlutterDriverService extends DriverService { _vmService = await _vmServiceConnector(uri, device: _device, logger: _logger); final DeviceLogReader logReader = await device.getLogReader(app: _applicationPackage); logReader.logLines.listen(_logger.printStatus); - - final vm_service.VM vm = await _vmService.service.getVM(); - logReader.appPid = vm.pid; + await logReader.provideVmService(_vmService); } @override diff --git a/packages/flutter_tools/lib/src/drive/web_driver_service.dart b/packages/flutter_tools/lib/src/drive/web_driver_service.dart index d95581be4fa..a0b5c7296a4 100644 --- a/packages/flutter_tools/lib/src/drive/web_driver_service.dart +++ b/packages/flutter_tools/lib/src/drive/web_driver_service.dart @@ -30,16 +30,13 @@ class WebDriverService extends DriverService { required ProcessUtils processUtils, required String dartSdkPath, required Logger logger, - required bool useImplicitPubspecResolution, }) : _processUtils = processUtils, _dartSdkPath = dartSdkPath, - _logger = logger, - _useImplicitPubspecResolution = useImplicitPubspecResolution; + _logger = logger; final ProcessUtils _processUtils; final String _dartSdkPath; final Logger _logger; - final bool _useImplicitPubspecResolution; late ResidentRunner _residentRunner; Uri? _webUri; @@ -81,6 +78,7 @@ class WebDriverService extends DriverService { hostname: debuggingOptions.hostname, webRenderer: debuggingOptions.webRenderer, webUseWasm: debuggingOptions.webUseWasm, + webHeaders: debuggingOptions.webHeaders, ) : DebuggingOptions.enabled( buildInfo, @@ -89,6 +87,7 @@ class WebDriverService extends DriverService { disablePortPublication: debuggingOptions.disablePortPublication, webRenderer: debuggingOptions.webRenderer, webUseWasm: debuggingOptions.webUseWasm, + webHeaders: debuggingOptions.webHeaders, ), stayResident: true, flutterProject: FlutterProject.current(), @@ -97,7 +96,6 @@ class WebDriverService extends DriverService { analytics: globals.analytics, logger: _logger, systemClock: globals.systemClock, - useImplicitPubspecResolution: _useImplicitPubspecResolution, ); final Completer appStartedCompleter = Completer.sync(); final Future runFuture = _residentRunner.run( diff --git a/packages/flutter_tools/lib/src/features.dart b/packages/flutter_tools/lib/src/features.dart index 7c86574bc8f..10e686c8b1a 100644 --- a/packages/flutter_tools/lib/src/features.dart +++ b/packages/flutter_tools/lib/src/features.dart @@ -54,6 +54,9 @@ abstract class FeatureFlags { /// Whether Swift Package Manager dependency management is enabled. bool get isSwiftPackageManagerEnabled => false; + /// Whether explicit package dependency management is enabled. + bool get isExplicitPackageDependenciesEnabled => false; + /// Whether a particular feature is enabled for the current channel. /// /// Prefer using one of the specific getters above instead of this API. @@ -74,6 +77,7 @@ const List allFeatures = [ nativeAssets, previewDevice, swiftPackageManager, + explicitPackageDependencies, ]; /// All current Flutter feature flags that can be configured. @@ -181,7 +185,31 @@ const Feature previewDevice = Feature( const Feature swiftPackageManager = Feature( name: 'support for Swift Package Manager for iOS and macOS', configSetting: 'enable-swift-package-manager', - environmentOverride: 'SWIFT_PACKAGE_MANAGER', + environmentOverride: 'FLUTTER_SWIFT_PACKAGE_MANAGER', + master: FeatureChannelSetting( + available: true, + ), + beta: FeatureChannelSetting( + available: true, + ), + stable: FeatureChannelSetting( + available: true, + ), +); + +/// Enable explicit resolution and generation of package dependencies. +const Feature explicitPackageDependencies = Feature( + name: 'support for dev_dependency plugins', + configSetting: 'explicit-package-dependencies', + extraHelpText: + 'Plugins that are resolved as result of being in "dev_dependencies" of a ' + 'package are not included in release builds of an app. By enabling this ' + 'feature, the synthetic "package:flutter_gen" can no longer be generated ' + 'and the legacy ".flutter-plugins" tool artifact is no longer generated.\n' + '\n' + 'See also:\n' + '* https://flutter.dev/to/flutter-plugins-configuration.\n' + '* https://flutter.dev/to/flutter-gen-deprecation.', master: FeatureChannelSetting( available: true, ), diff --git a/packages/flutter_tools/lib/src/flutter_cache.dart b/packages/flutter_tools/lib/src/flutter_cache.dart index e0946861f00..b8cd18a8572 100644 --- a/packages/flutter_tools/lib/src/flutter_cache.dart +++ b/packages/flutter_tools/lib/src/flutter_cache.dart @@ -910,7 +910,6 @@ const List> _androidBinaryDirs = >[ ['android-arm64-release', 'android-arm64-release/artifacts.zip'], ['android-x64-profile', 'android-x64-profile/artifacts.zip'], ['android-x64-release', 'android-x64-release/artifacts.zip'], - ['android-x86-jit-release', 'android-x86-jit-release/artifacts.zip'], ]; const List> _dartSdks = > [ diff --git a/packages/flutter_tools/lib/src/flutter_device_manager.dart b/packages/flutter_tools/lib/src/flutter_device_manager.dart index a0d33725709..9611519b4bf 100644 --- a/packages/flutter_tools/lib/src/flutter_device_manager.dart +++ b/packages/flutter_tools/lib/src/flutter_device_manager.dart @@ -53,7 +53,6 @@ class FlutterDeviceManager extends DeviceManager { required WindowsWorkflow windowsWorkflow, required CustomDevicesConfig customDevicesConfig, required TestCompilerNativeAssetsBuilder? nativeAssetsBuilder, - required bool useImplicitPubspecResolution, }) : deviceDiscoverers = [ AndroidDevices( logger: logger, @@ -80,7 +79,6 @@ class FlutterDeviceManager extends DeviceManager { logger: logger, artifacts: artifacts, nativeAssetsBuilder: nativeAssetsBuilder, - useImplicitPubspecResolution: useImplicitPubspecResolution, ), MacOSDevices( processManager: processManager, @@ -105,7 +103,6 @@ class FlutterDeviceManager extends DeviceManager { logger: logger, processManager: processManager, featureFlags: featureFlags, - useImplicitPubspecResolution: useImplicitPubspecResolution, ), LinuxDevices( platform: platform, @@ -134,7 +131,6 @@ class FlutterDeviceManager extends DeviceManager { processManager: processManager, logger: logger, config: customDevicesConfig, - useImplicitPubspecResolution: useImplicitPubspecResolution, ), ]; diff --git a/packages/flutter_tools/lib/src/flutter_features.dart b/packages/flutter_tools/lib/src/flutter_features.dart index df5b5c3be8f..9be6cf993e3 100644 --- a/packages/flutter_tools/lib/src/flutter_features.dart +++ b/packages/flutter_tools/lib/src/flutter_features.dart @@ -61,6 +61,9 @@ class FlutterFeatureFlags implements FeatureFlags { @override bool get isSwiftPackageManagerEnabled => isEnabled(swiftPackageManager); + @override + bool get isExplicitPackageDependenciesEnabled => isEnabled(explicitPackageDependencies); + @override bool isEnabled(Feature feature) { final String currentChannel = _flutterVersion.channel; diff --git a/packages/flutter_tools/lib/src/flutter_manifest.dart b/packages/flutter_tools/lib/src/flutter_manifest.dart index 537714826fd..ddc4ef2b6f2 100644 --- a/packages/flutter_tools/lib/src/flutter_manifest.dart +++ b/packages/flutter_tools/lib/src/flutter_manifest.dart @@ -64,6 +64,71 @@ class FlutterManifest { return pubspec; } + /// Creates a copy of the current manifest with some subset of properties + /// modified. + FlutterManifest copyWith({ + required Logger logger, + List? assets, + List? fonts, + List? shaders, + List? models, + List? deferredComponents, + }) { + final FlutterManifest copy = FlutterManifest._(logger: _logger); + copy._descriptor = {..._descriptor}; + copy._flutterDescriptor = {..._flutterDescriptor}; + + if (assets != null && assets.isNotEmpty) { + copy._flutterDescriptor['assets'] = YamlList.wrap( + [ + for (final AssetsEntry asset in assets) + asset.descriptor, + ], + ); + } + + if (fonts != null && fonts.isNotEmpty) { + copy._flutterDescriptor['fonts'] = YamlList.wrap( + >[ + for (final Font font in fonts) + font.descriptor, + ], + ); + } + + if (shaders != null && shaders.isNotEmpty) { + copy._flutterDescriptor['shaders'] = YamlList.wrap( + shaders.map( + (Uri uri) => uri.toString(), + ).toList(), + ); + } + + if (models != null && models.isNotEmpty) { + copy._flutterDescriptor['models'] = YamlList.wrap( + models.map( + (Uri uri) => uri.toString(), + ).toList(), + ); + } + + if (deferredComponents != null && deferredComponents.isNotEmpty) { + copy._flutterDescriptor['deferred-components'] = YamlList.wrap( + deferredComponents.map( + (DeferredComponent dc) => dc.descriptor, + ).toList() + ); + } + + copy._descriptor['flutter'] = YamlMap.wrap(copy._flutterDescriptor); + + if (!_validate(YamlMap.wrap(copy._descriptor), logger)) { + throw StateError('Generated invalid pubspec.yaml.'); + } + + return copy; + } + final Logger _logger; /// A map representation of the entire `pubspec.yaml` file. @@ -380,6 +445,10 @@ class FlutterManifest { } String? get defaultFlavor => _flutterDescriptor['default-flavor'] as String?; + + YamlMap toYaml() { + return YamlMap.wrap(_descriptor); + } } class Font { @@ -712,6 +781,21 @@ class AssetsEntry { final Set flavors; final List transformers; + Object? get descriptor { + if (transformers.isEmpty && flavors.isEmpty) { + return uri.toString(); + } + return { + _pathKey: uri.toString(), + if (flavors.isNotEmpty) + _flavorKey: flavors.toList(), + if (transformers.isNotEmpty) + _transformersKey: transformers.map( + (AssetTransformerEntry e) => e.descriptor, + ).toList(), + }; + } + static const String _pathKey = 'path'; static const String _flavorKey = 'flavors'; static const String _transformersKey = 'transformers'; @@ -858,6 +942,17 @@ final class AssetTransformerEntry { final String package; final List? args; + Map get descriptor { + return { + _kPackage: package, + if (args != null) + _kArgs: args, + }; + } + + static const String _kPackage = 'package'; + static const String _kArgs = 'args'; + static (AssetTransformerEntry? entry, List errors) tryParse(Object? yaml) { if (yaml == null) { return (null, ['Transformer entry is null.']); diff --git a/packages/flutter_tools/lib/src/flutter_plugins.dart b/packages/flutter_tools/lib/src/flutter_plugins.dart index f19d2450f1a..d95392c5619 100644 --- a/packages/flutter_tools/lib/src/flutter_plugins.dart +++ b/packages/flutter_tools/lib/src/flutter_plugins.dart @@ -21,6 +21,7 @@ import 'compute_dev_dependencies.dart'; import 'convert.dart'; import 'dart/language_version.dart'; import 'dart/package_map.dart'; +import 'dart/pub.dart'; import 'features.dart'; import 'globals.dart' as globals; import 'macos/darwin_dependency_management.dart'; @@ -88,30 +89,13 @@ Future _pluginFromPackage( /// Returns a list of all plugins to be registered with the provided [project]. /// -/// [useImplicitPubspecResolution] defines if legacy rules for traversing the -/// pub dependencies of a package implies, namely, that if `true`, all plugins -/// are assumed to be non-dev dependencies. Code that calls [findPlugins] in -/// order to obtain _other_ information about the plugins, such as whether a -/// plugin uses a specific language or platform can safely pass either `true` -/// or `false`; however a value of `false` _will_ cause `dart pub deps --json` -/// to trigger, which in turn could have other side-effects. -/// -/// Please reach out to matanlurey@ if you find you need: -/// ```dart -/// useImplicitPubspecResolution: true -/// ``` -/// -/// ... in order for your code to function, as that path is being deprecated: -/// . -/// -/// --- -/// /// If [throwOnError] is `true`, an empty package configuration is an error. Future> findPlugins( FlutterProject project, { - required bool useImplicitPubspecResolution, bool throwOnError = true, + bool? determineDevDependencies, }) async { + determineDevDependencies ??= featureFlags.isExplicitPackageDependenciesEnabled; final List plugins = []; final FileSystem fs = project.directory.fileSystem; final File packageConfigFile = findPackageConfigFileOrDefault(project.directory); @@ -121,16 +105,13 @@ Future> findPlugins( throwOnError: throwOnError, ); final Set devDependencies; - if (useImplicitPubspecResolution) { - // With --implicit-pubspec-resolution, we do not want to check for what - // plugins are dev dependencies and instead continue to assume the previous - // behavior (all plugins are non-dev dependencies). + if (!determineDevDependencies) { devDependencies = {}; } else { devDependencies = await computeExclusiveDevDependencies( - globals.processManager, + pub, logger: globals.logger, - projectPath: project.directory.path, + project: project, ); } for (final Package package in packageConfig.packages) { @@ -162,6 +143,7 @@ const String _kFlutterPluginsPathKey = 'path'; const String _kFlutterPluginsDependenciesKey = 'dependencies'; const String _kFlutterPluginsHasNativeBuildKey = 'native_build'; const String _kFlutterPluginsSharedDarwinSource = 'shared_darwin_source'; +const String _kFlutterPluginsDevDependencyKey = 'dev_dependency'; /// Writes the .flutter-plugins-dependencies file based on the list of plugins. /// If there aren't any plugins, then the files aren't written to disk. The resulting @@ -214,7 +196,8 @@ const String _kFlutterPluginsSharedDarwinSource = 'shared_darwin_source'; bool _writeFlutterPluginsList( FlutterProject project, List plugins, { - bool forceCocoaPodsOnly = false, + required bool swiftPackageManagerEnabledIos, + required bool swiftPackageManagerEnabledMacos, }) { final File pluginsFile = project.flutterPluginsDependenciesFile; if (plugins.isEmpty) { @@ -250,7 +233,11 @@ bool _writeFlutterPluginsList( result['dependencyGraph'] = _createPluginLegacyDependencyGraph(plugins); result['date_created'] = globals.systemClock.now().toString(); result['version'] = globals.flutterVersion.frameworkVersion; - result['swift_package_manager_enabled'] = !forceCocoaPodsOnly && project.usesSwiftPackageManager; + + result['swift_package_manager_enabled'] = { + 'ios': swiftPackageManagerEnabledIos, + 'macos': swiftPackageManagerEnabledMacos, + }; // Only notify if the plugins list has changed. [date_created] will always be different, // [version] is not relevant for this check. @@ -284,6 +271,7 @@ List> _createPluginMapOfPlatform( if (platformPlugin is NativeOrDartPlugin) _kFlutterPluginsHasNativeBuildKey: (platformPlugin as NativeOrDartPlugin).hasMethodChannel() || (platformPlugin as NativeOrDartPlugin).hasFfi(), _kFlutterPluginsDependenciesKey: [...plugin.dependencies.where(pluginNames.contains)], + _kFlutterPluginsDevDependencyKey: plugin.isDevDependency, }); } return pluginInfo; @@ -1056,19 +1044,33 @@ Future refreshPluginsList( bool iosPlatform = false, bool macOSPlatform = false, bool forceCocoaPodsOnly = false, - required bool useImplicitPubspecResolution, + bool? determineDevDependencies, + bool? generateLegacyPlugins, }) async { - final List plugins = await findPlugins(project, useImplicitPubspecResolution: useImplicitPubspecResolution); + final List plugins = await findPlugins(project, determineDevDependencies: determineDevDependencies); // Sort the plugins by name to keep ordering stable in generated files. plugins.sort((Plugin left, Plugin right) => left.name.compareTo(right.name)); // TODO(matanlurey): Remove once migration is complete. // Write the legacy plugin files to avoid breaking existing apps. - final bool legacyChanged = useImplicitPubspecResolution && _writeFlutterPluginsListLegacy(project, plugins); + generateLegacyPlugins ??= !featureFlags.isExplicitPackageDependenciesEnabled; + final bool legacyChanged = generateLegacyPlugins && _writeFlutterPluginsListLegacy(project, plugins); + + bool swiftPackageManagerEnabledIos = false; + bool swiftPackageManagerEnabledMacos = false; + if (!forceCocoaPodsOnly) { + if (iosPlatform) { + swiftPackageManagerEnabledIos = project.ios.usesSwiftPackageManager; + } + if (macOSPlatform) { + swiftPackageManagerEnabledMacos = project.macos.usesSwiftPackageManager; + } + } final bool changed = _writeFlutterPluginsList( project, plugins, - forceCocoaPodsOnly: forceCocoaPodsOnly, + swiftPackageManagerEnabledIos: swiftPackageManagerEnabledIos, + swiftPackageManagerEnabledMacos: swiftPackageManagerEnabledMacos, ); if (changed || legacyChanged || forceCocoaPodsOnly) { createPluginSymlinks(project, force: true); @@ -1101,7 +1103,7 @@ Future injectBuildTimePluginFilesForWebPlatform( FlutterProject project, { required Directory destination, }) async { - final List plugins = await findPlugins(project, useImplicitPubspecResolution: true); + final List plugins = await findPlugins(project); final Map> pluginsByPlatform = _resolvePluginImplementations(plugins, pluginResolutionType: _PluginResolutionType.nativeOrDart); await _writeWebPluginRegistrant(project, pluginsByPlatform[WebPlugin.kConfigKey]!, destination); } @@ -1120,7 +1122,6 @@ Future injectBuildTimePluginFilesForWebPlatform( /// Assumes [refreshPluginsList] has been called since last change to `pubspec.yaml`. Future injectPlugins( FlutterProject project, { - required bool useImplicitPubspecResolution, bool androidPlatform = false, bool iosPlatform = false, bool linuxPlatform = false, @@ -1129,7 +1130,7 @@ Future injectPlugins( Iterable? allowedPlugins, DarwinDependencyManagement? darwinDependencyManagement, }) async { - final List plugins = await findPlugins(project, useImplicitPubspecResolution: useImplicitPubspecResolution); + final List plugins = await findPlugins(project); final Map> pluginsByPlatform = _resolvePluginImplementations(plugins, pluginResolutionType: _PluginResolutionType.nativeOrDart); if (androidPlatform) { @@ -1371,7 +1372,7 @@ String? _validatePlugin(Plugin plugin, String platformKey, { if (_hasPluginInlineImpl(plugin, platformKey, pluginResolutionType: pluginResolutionType)) { return 'Plugin ${plugin.name}:$platformKey which provides an inline implementation ' 'cannot also reference a default implementation for $defaultImplPluginName. ' - 'Ask the maintainers of ${plugin.name} to either remove the implementation via `platforms: $platformKey:${pluginResolutionType == _PluginResolutionType.dart ? ' dartPluginClass' : '` `pluginClass` or `dartPLuginClass'}` ' + 'Ask the maintainers of ${plugin.name} to either remove the implementation via `platforms: $platformKey:${pluginResolutionType == _PluginResolutionType.dart ? ' dartPluginClass' : '` `pluginClass` or `dartPluginClass'}` ' 'or avoid referencing a default implementation via `platforms: $platformKey: default_package: $defaultImplPluginName`.\n'; } } @@ -1557,7 +1558,7 @@ Future generateMainDartWithPluginRegistrant( String currentMainUri, File mainFile, ) async { - final List plugins = await findPlugins(rootProject, useImplicitPubspecResolution: true); + final List plugins = await findPlugins(rootProject); final List resolutions = resolvePlatformImplementation( plugins, selectDartPluginsOnly: true, diff --git a/packages/flutter_tools/lib/src/ios/core_devices.dart b/packages/flutter_tools/lib/src/ios/core_devices.dart index e7eff51e285..5b820c88dbb 100644 --- a/packages/flutter_tools/lib/src/ios/core_devices.dart +++ b/packages/flutter_tools/lib/src/ios/core_devices.dart @@ -79,14 +79,30 @@ class IOSCoreDeviceControl { try { final RunResult result = await _processUtils.run(command, throwOnError: true); + bool isToolPossiblyShutdown = false; + if (_fileSystem is ErrorHandlingFileSystem) { + final FileSystem delegate = _fileSystem.fileSystem; + if (delegate is LocalFileSystem) { + isToolPossiblyShutdown = delegate.disposed; + } + } - if (!output.existsSync()) { + // It's possible that the tool is in the process of shutting down, which + // could result in the temp directory being deleted after the shutdown hooks run + // before we check if `output` exists. If this happens, we shouldn't crash + // but just carry on as if no devices were found as the tool will exit on + // its own. + // + // See https://github.com/flutter/flutter/issues/141892 for details. + if (!isToolPossiblyShutdown && !output.existsSync()) { _logger.printError('After running the command ${command.join(' ')} the file'); _logger.printError('${output.path} was expected to exist, but it did not.'); _logger.printError('The process exited with code ${result.exitCode} and'); _logger.printError('Stdout:\n\n${result.stdout.trim()}\n'); _logger.printError('Stderr:\n\n${result.stderr.trim()}'); throw StateError('Expected the file ${output.path} to exist but it did not'); + } else if (isToolPossiblyShutdown) { + return []; } final String stringOutput = output.readAsStringSync(); _logger.printTrace(stringOutput); diff --git a/packages/flutter_tools/lib/src/ios/devices.dart b/packages/flutter_tools/lib/src/ios/devices.dart index 554abf65e66..faff4c88176 100644 --- a/packages/flutter_tools/lib/src/ios/devices.dart +++ b/packages/flutter_tools/lib/src/ios/devices.dart @@ -1300,16 +1300,12 @@ class IOSDeviceLogReader extends DeviceLogReader { @override Stream get logLines => linesController.stream; - @override - FlutterVmService? get connectedVMService => _connectedVMService; - FlutterVmService? _connectedVMService; + FlutterVmService? _connectedVmService; @override - set connectedVMService(FlutterVmService? connectedVmService) { - if (connectedVmService != null) { - _listenToUnifiedLoggingEvents(connectedVmService); - } - _connectedVMService = connectedVmService; + Future provideVmService(FlutterVmService connectedVmService) async { + await _listenToUnifiedLoggingEvents(connectedVmService); + _connectedVmService = connectedVmService; } static const int minimumUniversalLoggingSdkVersion = 13; @@ -1360,7 +1356,7 @@ class IOSDeviceLogReader extends DeviceLogReader { // CoreDevice and has iOS 13 or greater. // When using `ios-deploy` and the Dart VM, prefer the more complete logs // from the attached debugger, if available. - if (connectedVMService != null && (_iosDeployDebugger == null || !_iosDeployDebugger!.debuggerAttached)) { + if (_connectedVmService != null && (_iosDeployDebugger == null || !_iosDeployDebugger!.debuggerAttached)) { return _IOSDeviceLogSources( primarySource: IOSDeviceLogSource.unifiedLogging, fallbackSource: IOSDeviceLogSource.iosDeploy, diff --git a/packages/flutter_tools/lib/src/ios/mac.dart b/packages/flutter_tools/lib/src/ios/mac.dart index 523555533f9..5dcc8ec40f8 100644 --- a/packages/flutter_tools/lib/src/ios/mac.dart +++ b/packages/flutter_tools/lib/src/ios/mac.dart @@ -18,6 +18,7 @@ import '../base/utils.dart'; import '../build_info.dart'; import '../cache.dart'; import '../device.dart'; +import '../features.dart'; import '../flutter_manifest.dart'; import '../flutter_plugins.dart'; import '../globals.dart' as globals; @@ -35,6 +36,7 @@ import 'application_package.dart'; import 'code_signing.dart'; import 'migrations/host_app_info_plist_migration.dart'; import 'migrations/ios_deployment_target_migration.dart'; +import 'migrations/metal_api_validation_migration.dart'; import 'migrations/project_base_configuration_migration.dart'; import 'migrations/project_build_location_migration.dart'; import 'migrations/remove_bitcode_migration.dart'; @@ -166,17 +168,18 @@ Future buildXcodeProject({ RemoveBitcodeMigration(app.project, globals.logger), XcodeThinBinaryBuildPhaseInputPathsMigration(app.project, globals.logger), UIApplicationMainDeprecationMigration(app.project, globals.logger), - if (project.usesSwiftPackageManager && app.project.flutterPluginSwiftPackageManifest.existsSync()) - SwiftPackageManagerIntegrationMigration( - app.project, - SupportedPlatform.ios, - buildInfo, - xcodeProjectInterpreter: globals.xcodeProjectInterpreter!, - logger: globals.logger, - fileSystem: globals.fs, - plistParser: globals.plistParser, - ), - SwiftPackageManagerGitignoreMigration(project, globals.logger), + SwiftPackageManagerIntegrationMigration( + app.project, + SupportedPlatform.ios, + buildInfo, + xcodeProjectInterpreter: globals.xcodeProjectInterpreter!, + logger: globals.logger, + fileSystem: globals.fs, + plistParser: globals.plistParser, + features: featureFlags, + ), + SwiftPackageManagerGitignoreMigration(project, globals.logger), + MetalAPIValidationMigrator.ios(app.project, globals.logger), ]; final ProjectMigration migration = ProjectMigration(migrators); @@ -267,7 +270,7 @@ Future buildXcodeProject({ targetOverride: targetOverride, buildInfo: buildInfo, ); - if (project.usesSwiftPackageManager) { + if (app.project.usesSwiftPackageManager) { final String? iosDeploymentTarget = buildSettings['IPHONEOS_DEPLOYMENT_TARGET']; if (iosDeploymentTarget != null) { SwiftPackageManager.updateMinimumDeployment( @@ -888,7 +891,7 @@ Future _handleIssues( logger.printError(missingPlatformInstructions(missingPlatform), emphasis: true); } else if (duplicateModules.isNotEmpty) { final bool usesCocoapods = xcodeProject.podfile.existsSync(); - final bool usesSwiftPackageManager = project.usesSwiftPackageManager; + final bool usesSwiftPackageManager = xcodeProject.usesSwiftPackageManager; if (usesCocoapods && usesSwiftPackageManager) { logger.printError( 'Your project uses both CocoaPods and Swift Package Manager, which can ' @@ -906,7 +909,7 @@ Future _handleIssues( } } else if (missingModules.isNotEmpty) { final bool usesCocoapods = xcodeProject.podfile.existsSync(); - final bool usesSwiftPackageManager = project.usesSwiftPackageManager; + final bool usesSwiftPackageManager = xcodeProject.usesSwiftPackageManager; if (usesCocoapods && !usesSwiftPackageManager) { final List swiftPackageOnlyPlugins = []; for (final String module in missingModules) { @@ -938,7 +941,7 @@ Future _isPluginSwiftPackageOnly({ required String pluginName, required FileSystem fileSystem, }) async { - final List plugins = await findPlugins(project, useImplicitPubspecResolution: true); + final List plugins = await findPlugins(project); final Plugin? matched = plugins .where((Plugin plugin) => plugin.name.toLowerCase() == pluginName.toLowerCase() && diff --git a/packages/flutter_tools/lib/src/ios/migrations/metal_api_validation_migration.dart b/packages/flutter_tools/lib/src/ios/migrations/metal_api_validation_migration.dart new file mode 100644 index 00000000000..0e343bc51ae --- /dev/null +++ b/packages/flutter_tools/lib/src/ios/migrations/metal_api_validation_migration.dart @@ -0,0 +1,50 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import '../../base/file_system.dart'; +import '../../base/project_migrator.dart'; +import '../../xcode_project.dart'; + +/// Remove Metal API validation setting that slows down applications. +class MetalAPIValidationMigrator extends ProjectMigrator { + MetalAPIValidationMigrator.ios( + IosProject project, + super.logger, + ) : _xcodeProjectScheme = project.xcodeProjectSchemeFile(); + + MetalAPIValidationMigrator.macos( + MacOSProject project, + super.logger, + ) : _xcodeProjectScheme = project.xcodeProjectSchemeFile(); + + final File _xcodeProjectScheme; + + + @override + Future migrate() async { + if (_xcodeProjectScheme.existsSync()) { + processFileLines(_xcodeProjectScheme); + } else { + logger.printTrace('default xcscheme file not found. Skipping Metal API validation migration.'); + } + } + + @override + String migrateFileContents(String fileContents) { + // If this string is anywhere in the file, assume that either we already + // migrated it or the developer made an intentional choice to opt in or out. + if (fileContents.contains('enableGPUValidationMode')) { + return fileContents; + } + // Look for a setting that is included in LaunchAction by default and + // insert the opt out after it. + final RegExp kDebugServiceExtension = RegExp('(\\s)*debugServiceExtension = "internal"\n'); + const String kValidationString = 'enableGPUValidationMode = "1"'; + return fileContents.replaceFirstMapped(kDebugServiceExtension, (Match match) { + final String group = match.group(0)!; + final int leadingCount = group.split('debugServiceExtension')[0].codeUnits.where((int codeUnit) => codeUnit == 32).length; + return '$group${' ' * leadingCount}$kValidationString\n'; + }); + } +} diff --git a/packages/flutter_tools/lib/src/ios/simulators.dart b/packages/flutter_tools/lib/src/ios/simulators.dart index 97d61857caf..f402b3bd7f8 100644 --- a/packages/flutter_tools/lib/src/ios/simulators.dart +++ b/packages/flutter_tools/lib/src/ios/simulators.dart @@ -26,6 +26,7 @@ import '../globals.dart' as globals; import '../macos/xcode.dart'; import '../project.dart'; import '../protocol_discovery.dart'; +import '../vmservice.dart'; import 'application_package.dart'; import 'mac.dart'; import 'plist_parser.dart'; @@ -1022,6 +1023,9 @@ class _IOSSimulatorLogReader extends DeviceLogReader { void dispose() { _stop(); } + + @override + Future provideVmService(FlutterVmService connectedVmService) async { } } class _IOSSimulatorDevicePortForwarder extends DevicePortForwarder { diff --git a/packages/flutter_tools/lib/src/isolated/native_assets/android/native_assets.dart b/packages/flutter_tools/lib/src/isolated/native_assets/android/native_assets.dart index bb88f52afdb..df7fec1423f 100644 --- a/packages/flutter_tools/lib/src/isolated/native_assets/android/native_assets.dart +++ b/packages/flutter_tools/lib/src/isolated/native_assets/android/native_assets.dart @@ -10,7 +10,6 @@ import '../../../android/gradle_utils.dart'; import '../../../base/common.dart'; import '../../../base/file_system.dart'; import '../../../build_info.dart' hide BuildMode; -import '../../../globals.dart' as globals; int targetAndroidNdkApi(Map environmentDefines) { return int.parse(environmentDefines[kMinSdkVersion] ?? minSdkVersion); @@ -21,52 +20,48 @@ Future copyNativeCodeAssetsAndroid( Map assetTargetLocations, FileSystem fileSystem, ) async { - if (assetTargetLocations.isNotEmpty) { - globals.logger - .printTrace('Copying native assets to ${buildUri.toFilePath()}.'); - final List jniArchDirs = [ - for (final AndroidArch androidArch in AndroidArch.values) - androidArch.archName, - ]; - for (final String jniArchDir in jniArchDirs) { - final Uri archUri = buildUri.resolve('jniLibs/lib/$jniArchDir/'); - await fileSystem.directory(archUri).create(recursive: true); - } - for (final MapEntry assetMapping - in assetTargetLocations.entries) { - final Uri source = assetMapping.key.file!; - final Uri target = (assetMapping.value.path as KernelAssetAbsolutePath).uri; - final AndroidArch androidArch = - _getAndroidArch(assetMapping.value.target); - final String jniArchDir = androidArch.archName; - final Uri archUri = buildUri.resolve('jniLibs/lib/$jniArchDir/'); - final Uri targetUri = archUri.resolveUri(target); - final String targetFullPath = targetUri.toFilePath(); - await fileSystem.file(source).copy(targetFullPath); - } - globals.logger.printTrace('Copying native assets done.'); + assert(assetTargetLocations.isNotEmpty); + final List jniArchDirs = [ + for (final AndroidArch androidArch in AndroidArch.values) + androidArch.archName, + ]; + for (final String jniArchDir in jniArchDirs) { + final Uri archUri = buildUri.resolve('jniLibs/lib/$jniArchDir/'); + await fileSystem.directory(archUri).create(recursive: true); + } + for (final MapEntry assetMapping + in assetTargetLocations.entries) { + final Uri source = assetMapping.key.file!; + final Uri target = (assetMapping.value.path as KernelAssetAbsolutePath).uri; + final AndroidArch androidArch = + _getAndroidArch(assetMapping.value.target.architecture); + final String jniArchDir = androidArch.archName; + final Uri archUri = buildUri.resolve('jniLibs/lib/$jniArchDir/'); + final Uri targetUri = archUri.resolveUri(target); + final String targetFullPath = targetUri.toFilePath(); + await fileSystem.file(source).copy(targetFullPath); } } -/// Get the [Target] for [androidArch]. -Target getNativeAndroidTarget(AndroidArch androidArch) { +/// Get the [Architecture] for [androidArch]. +Architecture getNativeAndroidArchitecture(AndroidArch androidArch) { return switch (androidArch) { - AndroidArch.armeabi_v7a => Target.androidArm, - AndroidArch.arm64_v8a => Target.androidArm64, - AndroidArch.x86 => Target.androidIA32, - AndroidArch.x86_64 => Target.androidX64, + AndroidArch.armeabi_v7a => Architecture.arm, + AndroidArch.arm64_v8a => Architecture.arm64, + AndroidArch.x86 => Architecture.ia32, + AndroidArch.x86_64 => Architecture.x64, }; } -/// Get the [AndroidArch] for [target]. -AndroidArch _getAndroidArch(Target target) { - return switch (target) { - Target.androidArm => AndroidArch.armeabi_v7a, - Target.androidArm64 => AndroidArch.arm64_v8a, - Target.androidIA32 => AndroidArch.x86, - Target.androidX64 => AndroidArch.x86_64, - Target.androidRiscv64 => throwToolExit('Android RISC-V not yet supported.'), - _ => throwToolExit('Invalid target: $target.'), +/// Get the [AndroidArch] for [architecture]. +AndroidArch _getAndroidArch(Architecture architecture) { + return switch (architecture) { + Architecture.arm => AndroidArch.armeabi_v7a, + Architecture.arm64 => AndroidArch.arm64_v8a, + Architecture.ia32 => AndroidArch.x86, + Architecture.x64 => AndroidArch.x86_64, + Architecture.riscv64 => throwToolExit('Android RISC-V not yet supported.'), + _ => throwToolExit('Invalid architecture: $architecture.'), }; } diff --git a/packages/flutter_tools/lib/src/isolated/native_assets/ios/native_assets.dart b/packages/flutter_tools/lib/src/isolated/native_assets/ios/native_assets.dart index a3df69900bf..1282b76dc8b 100644 --- a/packages/flutter_tools/lib/src/isolated/native_assets/ios/native_assets.dart +++ b/packages/flutter_tools/lib/src/isolated/native_assets/ios/native_assets.dart @@ -8,7 +8,6 @@ import 'package:native_assets_cli/code_assets_builder.dart'; import '../../../base/file_system.dart'; import '../../../build_info.dart' hide BuildMode; import '../../../build_info.dart' as build_info; -import '../../../globals.dart' as globals; import '../macos/native_assets_host.dart'; // TODO(dcharkes): Fetch minimum iOS version from somewhere. https://github.com/flutter/flutter/issues/145104 @@ -21,12 +20,12 @@ IOSSdk getIOSSdk(EnvironmentType environmentType) { }; } -/// Extract the [Target] from a [DarwinArch]. -Target getNativeIOSTarget(DarwinArch darwinArch) { +/// Extract the [Architecture] from a [DarwinArch]. +Architecture getNativeIOSArchitecture(DarwinArch darwinArch) { return switch (darwinArch) { - DarwinArch.armv7 => Target.iOSArm, - DarwinArch.arm64 => Target.iOSArm64, - DarwinArch.x86_64 => Target.iOSX64, + DarwinArch.armv7 => Architecture.arm, + DarwinArch.arm64 => Architecture.arm64, + DarwinArch.x86_64 => Architecture.x64, }; } @@ -115,47 +114,41 @@ Future copyNativeCodeAssetsIOS( build_info.BuildMode buildMode, FileSystem fileSystem, ) async { - if (assetTargetLocations.isNotEmpty) { - globals.logger - .printTrace('Copying native assets to ${buildUri.toFilePath()}.'); + assert(assetTargetLocations.isNotEmpty); + final Map oldToNewInstallNames = {}; + final List<(File, String, Directory)> dylibs = <(File, String, Directory)>[]; - final Map oldToNewInstallNames = {}; - final List<(File, String, Directory)> dylibs = <(File, String, Directory)>[]; - - for (final MapEntry> assetMapping - in assetTargetLocations.entries) { - final Uri target = (assetMapping.key as KernelAssetAbsolutePath).uri; - final List sources = [ - for (final CodeAsset source in assetMapping.value) - fileSystem.file(source.file) - ]; - final Uri targetUri = buildUri.resolveUri(target); - final File dylibFile = fileSystem.file(targetUri); - final Directory frameworkDir = dylibFile.parent; - if (!await frameworkDir.exists()) { - await frameworkDir.create(recursive: true); - } - await lipoDylibs(dylibFile, sources); - - final String dylibFileName = dylibFile.basename; - final String newInstallName = - '@rpath/$dylibFileName.framework/$dylibFileName'; - final Set oldInstallNames = await getInstallNamesDylib(dylibFile); - for (final String oldInstallName in oldInstallNames) { - oldToNewInstallNames[oldInstallName] = newInstallName; - } - dylibs.add((dylibFile, newInstallName, frameworkDir)); - - // TODO(knopp): Wire the value once there is a way to configure that in the hook. - // https://github.com/dart-lang/native/issues/1133 - await createInfoPlist(targetUri.pathSegments.last, frameworkDir, minimumIOSVersion: '12.0'); + for (final MapEntry> assetMapping + in assetTargetLocations.entries) { + final Uri target = (assetMapping.key as KernelAssetAbsolutePath).uri; + final List sources = [ + for (final CodeAsset source in assetMapping.value) + fileSystem.file(source.file) + ]; + final Uri targetUri = buildUri.resolveUri(target); + final File dylibFile = fileSystem.file(targetUri); + final Directory frameworkDir = dylibFile.parent; + if (!await frameworkDir.exists()) { + await frameworkDir.create(recursive: true); } + await lipoDylibs(dylibFile, sources); - for (final (File dylibFile, String newInstallName, Directory frameworkDir) in dylibs) { - await setInstallNamesDylib(dylibFile, newInstallName, oldToNewInstallNames); - await codesignDylib(codesignIdentity, buildMode, frameworkDir); + final String dylibFileName = dylibFile.basename; + final String newInstallName = + '@rpath/$dylibFileName.framework/$dylibFileName'; + final Set oldInstallNames = await getInstallNamesDylib(dylibFile); + for (final String oldInstallName in oldInstallNames) { + oldToNewInstallNames[oldInstallName] = newInstallName; } + dylibs.add((dylibFile, newInstallName, frameworkDir)); - globals.logger.printTrace('Copying native assets done.'); + // TODO(knopp): Wire the value once there is a way to configure that in the hook. + // https://github.com/dart-lang/native/issues/1133 + await createInfoPlist(targetUri.pathSegments.last, frameworkDir, minimumIOSVersion: '12.0'); + } + + for (final (File dylibFile, String newInstallName, Directory frameworkDir) in dylibs) { + await setInstallNamesDylib(dylibFile, newInstallName, oldToNewInstallNames); + await codesignDylib(codesignIdentity, buildMode, frameworkDir); } } diff --git a/packages/flutter_tools/lib/src/isolated/native_assets/macos/native_assets.dart b/packages/flutter_tools/lib/src/isolated/native_assets/macos/native_assets.dart index ff7d6305cd6..5024c1a2e03 100644 --- a/packages/flutter_tools/lib/src/isolated/native_assets/macos/native_assets.dart +++ b/packages/flutter_tools/lib/src/isolated/native_assets/macos/native_assets.dart @@ -8,17 +8,16 @@ import 'package:native_assets_cli/code_assets_builder.dart'; import '../../../base/file_system.dart'; import '../../../build_info.dart' hide BuildMode; import '../../../build_info.dart' as build_info; -import '../../../globals.dart' as globals; import 'native_assets_host.dart'; // TODO(dcharkes): Fetch minimum MacOS version from somewhere. https://github.com/flutter/flutter/issues/145104 const int targetMacOSVersion = 13; -/// Extract the [Target] from a [DarwinArch]. -Target getNativeMacOSTarget(DarwinArch darwinArch) { +/// Extract the [Architecture] from a [DarwinArch]. +Architecture getNativeMacOSArchitecture(DarwinArch darwinArch) { return switch (darwinArch) { - DarwinArch.arm64 => Target.macOSArm64, - DarwinArch.x86_64 => Target.macOSX64, + DarwinArch.arm64 => Architecture.arm64, + DarwinArch.x86_64 => Architecture.x64, DarwinArch.armv7 => throw Exception('Unknown DarwinArch: $darwinArch.'), }; } @@ -127,79 +126,73 @@ Future copyNativeCodeAssetsMacOS( build_info.BuildMode buildMode, FileSystem fileSystem, ) async { - if (assetTargetLocations.isNotEmpty) { - globals.logger.printTrace( - 'Copying native assets to ${buildUri.toFilePath()}.', - ); + assert(assetTargetLocations.isNotEmpty); - final Map oldToNewInstallNames = {}; - final List<(File, String, Directory)> dylibs = <(File, String, Directory)>[]; + final Map oldToNewInstallNames = {}; + final List<(File, String, Directory)> dylibs = <(File, String, Directory)>[]; - for (final MapEntry> assetMapping - in assetTargetLocations.entries) { - final Uri target = (assetMapping.key as KernelAssetAbsolutePath).uri; - final List sources = [ - for (final CodeAsset source in assetMapping.value) fileSystem.file(source.file), - ]; - final Uri targetUri = buildUri.resolveUri(target); - final String name = targetUri.pathSegments.last; - final Directory frameworkDir = fileSystem.file(targetUri).parent; - if (await frameworkDir.exists()) { - await frameworkDir.delete(recursive: true); - } - // MyFramework.framework/ frameworkDir - // MyFramework -> Versions/Current/MyFramework dylibLink - // Resources -> Versions/Current/Resources resourcesLink - // Versions/ versionsDir - // A/ versionADir - // MyFramework dylibFile - // Resources/ resourcesDir - // Info.plist - // Current -> A currentLink - final Directory versionsDir = frameworkDir.childDirectory('Versions'); - final Directory versionADir = versionsDir.childDirectory('A'); - final Directory resourcesDir = versionADir.childDirectory('Resources'); - await resourcesDir.create(recursive: true); - final File dylibFile = versionADir.childFile(name); - final Link currentLink = versionsDir.childLink('Current'); - await currentLink.create(fileSystem.path.relative( - versionADir.path, - from: currentLink.parent.path, - )); - final Link resourcesLink = frameworkDir.childLink('Resources'); - await resourcesLink.create(fileSystem.path.relative( - resourcesDir.path, - from: resourcesLink.parent.path, - )); - await lipoDylibs(dylibFile, sources); - final Link dylibLink = frameworkDir.childLink(name); - await dylibLink.create(fileSystem.path.relative( - versionsDir.childDirectory('Current').childFile(name).path, - from: dylibLink.parent.path, - )); - - final String dylibFileName = dylibFile.basename; - final String newInstallName = '@rpath/$dylibFileName.framework/$dylibFileName'; - final Set oldInstallNames = await getInstallNamesDylib(dylibFile); - for (final String oldInstallName in oldInstallNames) { - oldToNewInstallNames[oldInstallName] = newInstallName; - } - dylibs.add((dylibFile, newInstallName, frameworkDir)); - - await createInfoPlist(name, resourcesDir); + for (final MapEntry> assetMapping + in assetTargetLocations.entries) { + final Uri target = (assetMapping.key as KernelAssetAbsolutePath).uri; + final List sources = [ + for (final CodeAsset source in assetMapping.value) fileSystem.file(source.file), + ]; + final Uri targetUri = buildUri.resolveUri(target); + final String name = targetUri.pathSegments.last; + final Directory frameworkDir = fileSystem.file(targetUri).parent; + if (await frameworkDir.exists()) { + await frameworkDir.delete(recursive: true); } + // MyFramework.framework/ frameworkDir + // MyFramework -> Versions/Current/MyFramework dylibLink + // Resources -> Versions/Current/Resources resourcesLink + // Versions/ versionsDir + // A/ versionADir + // MyFramework dylibFile + // Resources/ resourcesDir + // Info.plist + // Current -> A currentLink + final Directory versionsDir = frameworkDir.childDirectory('Versions'); + final Directory versionADir = versionsDir.childDirectory('A'); + final Directory resourcesDir = versionADir.childDirectory('Resources'); + await resourcesDir.create(recursive: true); + final File dylibFile = versionADir.childFile(name); + final Link currentLink = versionsDir.childLink('Current'); + await currentLink.create(fileSystem.path.relative( + versionADir.path, + from: currentLink.parent.path, + )); + final Link resourcesLink = frameworkDir.childLink('Resources'); + await resourcesLink.create(fileSystem.path.relative( + resourcesDir.path, + from: resourcesLink.parent.path, + )); + await lipoDylibs(dylibFile, sources); + final Link dylibLink = frameworkDir.childLink(name); + await dylibLink.create(fileSystem.path.relative( + versionsDir.childDirectory('Current').childFile(name).path, + from: dylibLink.parent.path, + )); - for (final (File dylibFile, String newInstallName, Directory frameworkDir) in dylibs) { - await setInstallNamesDylib(dylibFile, newInstallName, oldToNewInstallNames); - // Do not code-sign the libraries here with identity. Code-signing - // for bundled dylibs is done in `macos_assemble.sh embed` because the - // "Flutter Assemble" target does not have access to the signing identity. - if (codesignIdentity != null) { - await codesignDylib(codesignIdentity, buildMode, frameworkDir); - } + final String dylibFileName = dylibFile.basename; + final String newInstallName = '@rpath/$dylibFileName.framework/$dylibFileName'; + final Set oldInstallNames = await getInstallNamesDylib(dylibFile); + for (final String oldInstallName in oldInstallNames) { + oldToNewInstallNames[oldInstallName] = newInstallName; } + dylibs.add((dylibFile, newInstallName, frameworkDir)); - globals.logger.printTrace('Copying native assets done.'); + await createInfoPlist(name, resourcesDir); + } + + for (final (File dylibFile, String newInstallName, Directory frameworkDir) in dylibs) { + await setInstallNamesDylib(dylibFile, newInstallName, oldToNewInstallNames); + // Do not code-sign the libraries here with identity. Code-signing + // for bundled dylibs is done in `macos_assemble.sh embed` because the + // "Flutter Assemble" target does not have access to the signing identity. + if (codesignIdentity != null) { + await codesignDylib(codesignIdentity, buildMode, frameworkDir); + } } } @@ -221,40 +214,34 @@ Future copyNativeCodeAssetsMacOSFlutterTester( build_info.BuildMode buildMode, FileSystem fileSystem, ) async { - if (assetTargetLocations.isNotEmpty) { - globals.logger.printTrace( - 'Copying native assets to ${buildUri.toFilePath()}.', - ); + assert(assetTargetLocations.isNotEmpty); - final Map oldToNewInstallNames = {}; - final List<(File, String)> dylibs = <(File, String)>[]; + final Map oldToNewInstallNames = {}; + final List<(File, String)> dylibs = <(File, String)>[]; - for (final MapEntry> assetMapping - in assetTargetLocations.entries) { - final Uri target = (assetMapping.key as KernelAssetAbsolutePath).uri; - final List sources = [ - for (final CodeAsset source in assetMapping.value) fileSystem.file(source.file), - ]; - final Uri targetUri = buildUri.resolveUri(target); - final File dylibFile = fileSystem.file(targetUri); - final Directory targetParent = dylibFile.parent; - if (!await targetParent.exists()) { - await targetParent.create(recursive: true); - } - await lipoDylibs(dylibFile, sources); - final String newInstallName = dylibFile.path; - final Set oldInstallNames = await getInstallNamesDylib(dylibFile); - for (final String oldInstallName in oldInstallNames) { - oldToNewInstallNames[oldInstallName] = newInstallName; - } - dylibs.add((dylibFile, newInstallName)); + for (final MapEntry> assetMapping + in assetTargetLocations.entries) { + final Uri target = (assetMapping.key as KernelAssetAbsolutePath).uri; + final List sources = [ + for (final CodeAsset source in assetMapping.value) fileSystem.file(source.file), + ]; + final Uri targetUri = buildUri.resolveUri(target); + final File dylibFile = fileSystem.file(targetUri); + final Directory targetParent = dylibFile.parent; + if (!await targetParent.exists()) { + await targetParent.create(recursive: true); } - - for (final (File dylibFile, String newInstallName) in dylibs) { - await setInstallNamesDylib(dylibFile, newInstallName, oldToNewInstallNames); - await codesignDylib(codesignIdentity, buildMode, dylibFile); + await lipoDylibs(dylibFile, sources); + final String newInstallName = dylibFile.path; + final Set oldInstallNames = await getInstallNamesDylib(dylibFile); + for (final String oldInstallName in oldInstallNames) { + oldToNewInstallNames[oldInstallName] = newInstallName; } + dylibs.add((dylibFile, newInstallName)); + } - globals.logger.printTrace('Copying native assets done.'); + for (final (File dylibFile, String newInstallName) in dylibs) { + await setInstallNamesDylib(dylibFile, newInstallName, oldToNewInstallNames); + await codesignDylib(codesignIdentity, buildMode, dylibFile); } } diff --git a/packages/flutter_tools/lib/src/isolated/native_assets/native_assets.dart b/packages/flutter_tools/lib/src/isolated/native_assets/native_assets.dart index 31f9908f4bc..57c9820479b 100644 --- a/packages/flutter_tools/lib/src/isolated/native_assets/native_assets.dart +++ b/packages/flutter_tools/lib/src/isolated/native_assets/native_assets.dart @@ -17,11 +17,10 @@ import '../../base/platform.dart'; import '../../build_info.dart' as build_info; import '../../build_system/exceptions.dart'; import '../../cache.dart'; +import '../../convert.dart'; import '../../features.dart'; import '../../globals.dart' as globals; import '../../macos/xcode.dart' as xcode; -import '../../resident_runner.dart'; -import '../../run_hot.dart'; import 'android/native_assets.dart'; import 'ios/native_assets.dart'; import 'linux/native_assets.dart'; @@ -35,40 +34,57 @@ import 'windows/native_assets.dart'; /// again. final class DartBuildResult { const DartBuildResult(this.codeAssets, this.dependencies); + const DartBuildResult.empty() : codeAssets = const [], dependencies = const []; + factory DartBuildResult.fromJson(Map json) { + final List dependencies = [ + for (final Object? encodedUri in json['dependencies']! as List) + Uri.parse(encodedUri! as String), + ]; + final List codeAssets = [ + for (final Object? json in json['code_assets']! as List) + CodeAsset.fromEncoded(EncodedAsset.fromJson(json! as Map)), + ]; + return DartBuildResult(codeAssets, dependencies); + } + final List codeAssets; final List dependencies; + + Map toJson() => { + 'dependencies': [ + for (final Uri dep in dependencies) dep.toString(), + ], + 'code_assets': [ + for (final CodeAsset code in codeAssets) code.encode().toJson(), + ], + }; + + /// The files that eventually should be bundled with the app. + List get filesToBeBundled => [ + for (final CodeAsset code in codeAssets) + if (code.linkMode is DynamicLoadingBundled) code.file!, + ]; } /// Invokes the build of all transitive Dart packages and prepares code assets /// to be included in the native build. -Future<(DartBuildResult, Uri)> runFlutterSpecificDartBuild({ +Future runFlutterSpecificDartBuild({ required Map environmentDefines, required FlutterNativeAssetsBuildRunner buildRunner, required build_info.TargetPlatform targetPlatform, required Uri projectUri, - Uri? nativeAssetsYamlUri, required FileSystem fileSystem, }) async { - final OS targetOS = _getNativeOSFromTargetPlatfrorm(targetPlatform); + final OS targetOS = getNativeOSFromTargetPlatform(targetPlatform); final Uri buildUri = nativeAssetsBuildUri(projectUri, targetOS); final Directory buildDir = fileSystem.directory(buildUri); final bool flutterTester = targetPlatform == build_info.TargetPlatform.tester; - if (nativeAssetsYamlUri == null) { - // Only `flutter test` uses the - // `build/native_assets//native_assets.yaml` file which uses absolute - // paths to the shared libraries. - // - // testCompilerBuildNativeAssets() passes `null` - assert(flutterTester); - nativeAssetsYamlUri ??= buildUri.resolve('native_assets.yaml'); - } - if (!await buildDir.exists()) { // Ensure the folder exists so the native build system can copy it even // if there's no native assets. @@ -76,107 +92,43 @@ Future<(DartBuildResult, Uri)> runFlutterSpecificDartBuild({ } if (!await _nativeBuildRequired(buildRunner)) { - await writeNativeAssetsYaml( - KernelAssets(), nativeAssetsYamlUri, fileSystem); - return (const DartBuildResult.empty(), nativeAssetsYamlUri); + return const DartBuildResult.empty(); } - final build_info.BuildMode buildMode; - if (flutterTester) { - buildMode = build_info.BuildMode.debug; - } else { - final String? environmentBuildMode = - environmentDefines[build_info.kBuildMode]; - if (environmentBuildMode == null) { - throw MissingDefineException(build_info.kBuildMode, 'native_assets'); - } - buildMode = build_info.BuildMode.fromCliName(environmentBuildMode); - } - final List targets = flutterTester - ? [Target.current] - : _targetsForOS(targetPlatform, targetOS, environmentDefines); - final DartBuildResult result = targets.isEmpty + final build_info.BuildMode buildMode = _getBuildMode(environmentDefines, flutterTester); + final List architectures = flutterTester + ? [Architecture.current] + : _architecturesForOS(targetPlatform, targetOS, environmentDefines); + final DartBuildResult result = architectures.isEmpty ? const DartBuildResult.empty() : await _runDartBuild( environmentDefines: environmentDefines, buildRunner: buildRunner, - targets: targets, + architectures: architectures, projectUri: projectUri, buildMode: _nativeAssetsBuildMode(buildMode), fileSystem: fileSystem, targetOS: targetOS); - - final String? codesignIdentity = - environmentDefines[build_info.kCodesignIdentity]; - - final Map assetTargetLocations = - _assetTargetLocationsForOS( - targetOS, result.codeAssets, flutterTester, buildUri); - await _copyNativeCodeAssetsForOS(targetOS, buildUri, buildMode, fileSystem, - assetTargetLocations, codesignIdentity, flutterTester); - final KernelAssets vmAssetMapping = - KernelAssets(assetTargetLocations.values.toList()); - await writeNativeAssetsYaml(vmAssetMapping, nativeAssetsYamlUri, fileSystem); - return (result, nativeAssetsYamlUri); + return result; } -Future runFlutterSpecificDartDryRunOnPlatforms({ +Future installCodeAssets({ + required DartBuildResult dartBuildResult, + required Map environmentDefines, + required build_info.TargetPlatform targetPlatform, required Uri projectUri, required FileSystem fileSystem, - required FlutterNativeAssetsBuildRunner buildRunner, - required List targetPlatforms, + required Uri nativeAssetsFileUri, }) async { - if (!await _nativeBuildRequired(buildRunner)) { - return null; - } + final OS targetOS = getNativeOSFromTargetPlatform(targetPlatform); + final Uri buildUri = nativeAssetsBuildUri(projectUri, targetOS); + final bool flutterTester = targetPlatform == build_info.TargetPlatform.tester; + final build_info.BuildMode buildMode = _getBuildMode(environmentDefines, flutterTester); - final Map assetTargetLocations = - {}; - for (final build_info.TargetPlatform targetPlatform in targetPlatforms) { - // This dry-run functionality is only used in the `flutter run` - // implementation (not in `flutter build` or `flutter test`). - // - // Though we can end up with `flutterTester == true` if someone uses the - // `flutter-tester` device via `flutter run -d flutter-tester` (which mainly - // happens in tests) - final bool flutterTester = - targetPlatform == build_info.TargetPlatform.tester; - - final OS targetOS = _getNativeOSFromTargetPlatfrorm(targetPlatform); - if (targetOS != OS.macOS && - targetOS != OS.windows && - targetOS != OS.linux && - targetOS != OS.android && - targetOS != OS.iOS) { - await ensureNoNativeAssetsOrOsIsSupported( - projectUri, - targetPlatform.toString(), - fileSystem, - buildRunner, - ); - } - - final Uri buildUri = nativeAssetsBuildUri(projectUri, targetOS); - final DartBuildResult result = await _runDartDryRunBuild( - buildRunner: buildRunner, - projectUri: projectUri, - fileSystem: fileSystem, - targetOS: targetOS); - assetTargetLocations.addAll(_assetTargetLocationsForOS( - targetOS, result.codeAssets, flutterTester, buildUri)); - } - - final Uri buildUri = targetPlatforms.length == 1 - ? nativeAssetsBuildUri( - projectUri, _getNativeOSFromTargetPlatfrorm(targetPlatforms.single)) - : _buildUriMultiple(projectUri); - final Uri nativeAssetsYamlUri = buildUri.resolve('native_assets.yaml'); - await writeNativeAssetsYaml( - KernelAssets(assetTargetLocations.values.toList()), - nativeAssetsYamlUri, - fileSystem, - ); - return nativeAssetsYamlUri; + final String? codesignIdentity = environmentDefines[build_info.kCodesignIdentity]; + final Map assetTargetLocations = assetTargetLocationsForOS(targetOS, dartBuildResult.codeAssets, flutterTester, buildUri); + await _copyNativeCodeAssetsForOS(targetOS, buildUri, buildMode, fileSystem, assetTargetLocations, codesignIdentity, flutterTester); + await _writeNativeAssetsJson(assetTargetLocations.values.toList(), nativeAssetsFileUri, fileSystem,); } /// Programmatic API to be used by Dart launchers to invoke native builds. @@ -186,23 +138,13 @@ Future runFlutterSpecificDartDryRunOnPlatforms({ abstract interface class FlutterNativeAssetsBuildRunner { /// Whether the project has a `.dart_tools/package_config.json`. /// - /// If there is no package config, [packagesWithNativeAssets], [build], and - /// [buildDryRun] must not be invoked. + /// If there is no package config, [packagesWithNativeAssets], [build] and + /// [link] must not be invoked. Future hasPackageConfig(); /// All packages in the transitive dependencies that have a `build.dart`. Future> packagesWithNativeAssets(); - /// Runs all [packagesWithNativeAssets] `build.dart` in dry run. - Future buildDryRun({ - required List supportedAssetTypes, - required BuildConfigCreator configCreator, - required BuildValidator buildValidator, - required bool includeParentEnvironment, - required OS targetOS, - required Uri workingDirectory, - }); - /// Runs all [packagesWithNativeAssets] `build.dart`. Future build({ required List supportedAssetTypes, @@ -294,30 +236,6 @@ class FlutterNativeAssetsBuildRunnerImpl implements FlutterNativeAssetsBuildRunn } @override - Future buildDryRun({ - required List supportedAssetTypes, - required BuildConfigCreator configCreator, - required BuildValidator buildValidator, - required bool includeParentEnvironment, - required OS targetOS, - required Uri workingDirectory, - }) { - final PackageLayout packageLayout = PackageLayout.fromPackageConfig( - packageConfig, - Uri.file(packageConfigPath), - ); - return _buildRunner.buildDryRun( - supportedAssetTypes: supportedAssetTypes, - configCreator: configCreator, - buildValidator: buildValidator, - includeParentEnvironment: includeParentEnvironment, - targetOS: targetOS, - workingDirectory: workingDirectory, - packageLayout: packageLayout, - linkingEnabled: false, // Dry run is only used in JIT mode. - ); - } - @override Future build({ required List supportedAssetTypes, @@ -405,14 +323,14 @@ class FlutterNativeAssetsBuildRunnerImpl implements FlutterNativeAssetsBuildRunn }(); } -Future writeNativeAssetsYaml( - KernelAssets assets, - Uri nativeAssetsYamlUri, +Future _writeNativeAssetsJson( + List assets, + Uri nativeAssetsJsonUri, FileSystem fileSystem, ) async { - globals.logger.printTrace('Writing native assets yaml to $nativeAssetsYamlUri.'); - final String nativeAssetsDartContents = assets.toNativeAssetsFile(); - final File nativeAssetsFile = fileSystem.file(nativeAssetsYamlUri); + globals.logger.printTrace('Writing native assets json to $nativeAssetsJsonUri.'); + final String nativeAssetsDartContents = _toNativeAssetsJsonFile(assets); + final File nativeAssetsFile = fileSystem.file(nativeAssetsJsonUri); final Directory parentDirectory = nativeAssetsFile.parent; if (!await parentDirectory.exists()) { await parentDirectory.create(recursive: true); @@ -422,6 +340,29 @@ Future writeNativeAssetsYaml( return nativeAssetsFile.uri; } +String _toNativeAssetsJsonFile(List kernelAssets) { + final Map> assetsPerTarget = >{}; + for (final KernelAsset asset in kernelAssets) { + assetsPerTarget.putIfAbsent(asset.target, () => []).add(asset); + } + + const String formatVersionKey = 'format-version'; + const String nativeAssetsKey = 'native-assets'; + + // See assets/native_assets.cc in the engine for the expected format. + final Map jsonContents = { + formatVersionKey: const [1, 0, 0], + nativeAssetsKey: >>{ + for (final MapEntry> entry in assetsPerTarget.entries) + entry.key.toString(): >{ + for (final KernelAsset e in entry.value) e.id: e.path.toJson(), + } + }, + }; + + return jsonEncode(jsonContents); +} + /// Select the native asset build mode for a given Flutter build mode. BuildMode _nativeAssetsBuildMode(build_info.BuildMode buildMode) { switch (buildMode) { @@ -505,54 +446,6 @@ Uri nativeAssetsBuildUri(Uri projectUri, OS os) { return projectUri.resolve('$buildDir/native_assets/$os/'); } -/// Gets the native asset id to dylib mapping to embed in the kernel file. -/// -/// Run hot compiles a kernel file that is pushed to the device after hot -/// restart. We need to embed the native assets mapping in order to access -/// native assets after hot restart. -class HotRunnerNativeAssetsBuilderImpl implements HotRunnerNativeAssetsBuilder { - const HotRunnerNativeAssetsBuilderImpl(); - - @override - Future dryRun({ - required Uri projectUri, - required FileSystem fileSystem, - required List flutterDevices, - required String packageConfigPath, - required PackageConfig packageConfig, - required Logger logger, - }) async { - final FlutterNativeAssetsBuildRunner buildRunner = - FlutterNativeAssetsBuildRunnerImpl( - projectUri, - packageConfigPath, - packageConfig, - fileSystem, - globals.logger, - ); - - // If `flutter run -d all` is used then we may have multiple OSes. - final List targetPlatforms = flutterDevices - .map((FlutterDevice d) => d.targetPlatform) - .nonNulls - .toList(); - - return runFlutterSpecificDartDryRunOnPlatforms( - projectUri: projectUri, - fileSystem: fileSystem, - buildRunner: buildRunner, - targetPlatforms: targetPlatforms, - ); - } -} - -/// With `flutter run -d all` we need a place to store the native assets -/// mapping for multiple OSes combined. -Uri _buildUriMultiple(Uri projectUri) { - final String buildDir = build_info.getBuildDirectory(); - return projectUri.resolve('$buildDir/native_assets/multiple/'); -} - Map _assetTargetLocationsWindowsLinux( List assets, Uri? absolutePath, @@ -602,7 +495,7 @@ KernelAsset _targetLocationSingleArchitecture( ); } -Map _assetTargetLocationsForOS( +Map assetTargetLocationsForOS( OS targetOS, List codeAssets, bool flutterTester, Uri buildUri) { switch (targetOS) { case OS.windows: @@ -629,6 +522,21 @@ Future _copyNativeCodeAssetsForOS( Map assetTargetLocations, String? codesignIdentity, bool flutterTester) async { + // We only have to copy code assets that are bundled within the app. + // If a code asset that use a linking mode of [LookupInProcess], + // [LookupInExecutable] or [DynamicLoadingSystem] do not have anything to + // bundle as part of the app. + assetTargetLocations = { + for (final CodeAsset codeAsset in assetTargetLocations.keys) + if (codeAsset.linkMode is DynamicLoadingBundled) + codeAsset: assetTargetLocations[codeAsset]!, + }; + + if (assetTargetLocations.isEmpty) { + return; + } + + globals.logger.printTrace('Copying native assets to ${buildUri.toFilePath()}.'); final List codeAssets = assetTargetLocations.keys.toList(); switch (targetOS) { case OS.windows: @@ -673,6 +581,7 @@ Future _copyNativeCodeAssetsForOS( default: throw StateError('This should be unreachable.'); } + globals.logger.printTrace('Copying native assets done.'); } /// Invokes the build of all transitive Dart packages. @@ -682,20 +591,23 @@ Future _copyNativeCodeAssetsForOS( Future _runDartBuild({ required Map environmentDefines, required FlutterNativeAssetsBuildRunner buildRunner, - required List targets, + required List architectures, required Uri projectUri, required BuildMode buildMode, required FileSystem fileSystem, - required OS targetOS, + required OS? targetOS, }) async { final bool linkingEnabled = buildMode == BuildMode.release; - final String targetString = targets.length == 1 - ? targets.single.toString() - : targets.toList().toString(); + + final String architectureString = architectures.length == 1 + ? architectures.single.toString() + : architectures.toList().toString(); + globals.logger - .printTrace('Building native assets for $targetString $buildMode.'); + .printTrace('Building native assets for $targetOS $architectureString $buildMode.'); final List assets = []; final Set dependencies = {}; + final build_info.EnvironmentType? environmentType; if (targetOS == OS.iOS) { final String? sdkRoot = environmentDefines[build_info.kSdkRoot]; @@ -719,12 +631,12 @@ Future _runDartBuild({ final int? macOSVersion = targetOS == OS.macOS ? targetMacOSVersion : null; final IOSSdk? iOSSdk = targetOS == OS.iOS ? getIOSSdk(environmentType!) : null; - for (final Target target in targets) { + for (final Architecture architecture in architectures) { final BuildResult? buildResult = await buildRunner.build( supportedAssetTypes: [CodeAsset.type], configCreator: () => BuildConfigBuilder() ..setupCodeConfig( - targetArchitecture: target.architecture, + targetArchitecture: architecture, linkModePreference: LinkModePreference.dynamic, cCompilerConfig: cCompilerConfig, targetAndroidNdkApi: androidNdkApi, @@ -741,7 +653,7 @@ Future _runDartBuild({ applicationAssetValidator: (List assets) async => [ ...await validateCodeAssetInApplication(assets), ], - targetOS: target.os, + targetOS: targetOS!, buildMode: buildMode, workingDirectory: projectUri, includeParentEnvironment: true, @@ -750,14 +662,15 @@ Future _runDartBuild({ if (buildResult == null) { _throwNativeAssetsBuildFailed(); } - assets.addAll(buildResult.encodedAssets); dependencies.addAll(buildResult.dependencies); - if (linkingEnabled) { + if (!linkingEnabled) { + assets.addAll(buildResult.encodedAssets); + } else { final LinkResult? linkResult = await buildRunner.link( supportedAssetTypes: [CodeAsset.type], configCreator: () => LinkConfigBuilder() ..setupCodeConfig( - targetArchitecture: target.architecture, + targetArchitecture: architecture, linkModePreference: LinkModePreference.dynamic, cCompilerConfig: cCompilerConfig, targetAndroidNdkApi: androidNdkApi, @@ -793,55 +706,17 @@ Future _runDartBuild({ .map(CodeAsset.fromEncoded) .toList(); globals.logger - .printTrace('Building native assets for $targetString $buildMode done.'); + .printTrace('Building native assets for $targetOS $architectureString $buildMode done.'); return DartBuildResult(codeAssets, dependencies.toList()); } -Future _runDartDryRunBuild({ - required FlutterNativeAssetsBuildRunner buildRunner, - required Uri projectUri, - required FileSystem fileSystem, - required OS targetOS, -}) async { - globals.logger.printTrace('Dry running native assets for $targetOS.'); - final List assets = []; - final Set dependencies = {}; - final BuildDryRunResult? buildResult = await buildRunner.buildDryRun( - supportedAssetTypes: [CodeAsset.type], - configCreator: () => BuildConfigBuilder() - ..setupCodeConfig( - targetArchitecture: null, - linkModePreference: LinkModePreference.dynamic, - ), - buildValidator: (BuildConfig config, BuildOutput output) async => [ - ...await validateCodeAssetBuildOutput(config, output), - ], - workingDirectory: projectUri, - targetOS: targetOS, - includeParentEnvironment: true, - ); - if (buildResult == null) { - _throwNativeAssetsBuildDryRunFailed(); - } - assets.addAll(buildResult.encodedAssets); - - final List codeAssets = assets - .where((EncodedAsset asset) => asset.type == CodeAsset.type) - .map(CodeAsset.fromEncoded) - .toList(); - globals.logger.printTrace('Dry running native assets for $targetOS done.'); - return DartBuildResult( - _expandCodeAssetsToAllArchitectures(codeAssets), - dependencies.toList()); -} - -List _targetsForOS(build_info.TargetPlatform targetPlatform, +List _architecturesForOS(build_info.TargetPlatform targetPlatform, OS targetOS, Map environmentDefines) { switch (targetOS) { case OS.linux: - return [_getNativeTarget(targetPlatform)]; + return [_getNativeArchitecture(targetPlatform)]; case OS.windows: - return [_getNativeTarget(targetPlatform)]; + return [_getNativeArchitecture(targetPlatform)]; case OS.macOS: final List darwinArchs = _emptyToNull(environmentDefines[build_info.kDarwinArchs]) @@ -852,7 +727,7 @@ List _targetsForOS(build_info.TargetPlatform targetPlatform, build_info.DarwinArch.x86_64, build_info.DarwinArch.arm64 ]; - return darwinArchs.map(getNativeMacOSTarget).toList(); + return darwinArchs.map(getNativeMacOSArchitecture).toList(); case OS.android: final String? androidArchsEnvironment = environmentDefines[build_info.kAndroidArchs]; @@ -860,7 +735,7 @@ List _targetsForOS(build_info.TargetPlatform targetPlatform, targetPlatform, androidArchsEnvironment, ); - return androidArchs.map(getNativeAndroidTarget).toList(); + return androidArchs.map(getNativeAndroidArchitecture).toList(); case OS.iOS: final List iosArchs = _emptyToNull(environmentDefines[build_info.kIosArchs]) @@ -868,24 +743,22 @@ List _targetsForOS(build_info.TargetPlatform targetPlatform, .map(build_info.getIOSArchForName) .toList() ?? [build_info.DarwinArch.arm64]; - return iosArchs.map(getNativeIOSTarget).toList(); + return iosArchs.map(getNativeIOSArchitecture).toList(); default: // TODO(dacoharkes): Implement other OSes. https://github.com/flutter/flutter/issues/129757 // Write the file we claim to have in the [outputs]. - return []; + return []; } } -Target _getNativeTarget(build_info.TargetPlatform targetPlatform) { +Architecture _getNativeArchitecture(build_info.TargetPlatform targetPlatform) { switch (targetPlatform) { case build_info.TargetPlatform.linux_x64: - return Target.linuxX64; - case build_info.TargetPlatform.linux_arm64: - return Target.linuxArm64; case build_info.TargetPlatform.windows_x64: - return Target.windowsX64; + return Architecture.x64; + case build_info.TargetPlatform.linux_arm64: case build_info.TargetPlatform.windows_arm64: - return Target.windowsArm64; + return Architecture.arm64; case build_info.TargetPlatform.android: case build_info.TargetPlatform.ios: case build_info.TargetPlatform.darwin: @@ -907,29 +780,19 @@ Future _copyNativeCodeAssetsToBundleOnWindowsLinux( build_info.BuildMode buildMode, FileSystem fileSystem, ) async { - globals.logger.printTrace('copyNativeCodeAssetsToBundleOnWindowsLinux()'); - if (assetTargetLocations.isNotEmpty) { - globals.logger.printTrace('Copying native assets to ${buildUri.toFilePath()}.'); - final Directory buildDir = fileSystem.directory(buildUri.toFilePath()); - if (!buildDir.existsSync()) { - buildDir.createSync(recursive: true); - } - for (final MapEntry assetMapping in assetTargetLocations.entries) { - final Uri source = assetMapping.key.file!; - final Uri target = (assetMapping.value.path as KernelAssetAbsolutePath).uri; - final Uri targetUri = buildUri.resolveUri(target); - final String targetFullPath = targetUri.toFilePath(); - await fileSystem.file(source).copy(targetFullPath); - globals.logger.printTrace('copyNativeCodeAssetsToBundleOnWindowsLinux(): copied $source to $targetFullPath'); - } - globals.logger.printTrace('Copying native assets done.'); - } -} + assert(assetTargetLocations.isNotEmpty); -Never _throwNativeAssetsBuildDryRunFailed() { - throwToolExit( - 'Building (dry run) native assets failed. See the logs for more details.', - ); + final Directory buildDir = fileSystem.directory(buildUri.toFilePath()); + if (!buildDir.existsSync()) { + buildDir.createSync(recursive: true); + } + for (final MapEntry assetMapping in assetTargetLocations.entries) { + final Uri source = assetMapping.key.file!; + final Uri target = (assetMapping.value.path as KernelAssetAbsolutePath).uri; + final Uri targetUri = buildUri.resolveUri(target); + final String targetFullPath = targetUri.toFilePath(); + await fileSystem.file(source).copy(targetFullPath); + } } Never _throwNativeAssetsBuildFailed() { @@ -944,7 +807,7 @@ Never _throwNativeAssetsLinkFailed() { ); } -OS _getNativeOSFromTargetPlatfrorm(build_info.TargetPlatform platform) { +OS getNativeOSFromTargetPlatform(build_info.TargetPlatform platform) { switch (platform) { case build_info.TargetPlatform.ios: return OS.iOS; @@ -1022,15 +885,6 @@ String? _emptyToNull(String? input) { return input; } -List _expandCodeAssetsToAllArchitectures(List codeAssets) { - assert(codeAssets.every((CodeAsset asset) => asset.architecture == null)); - return [ - for (final CodeAsset codeAsset in codeAssets) - for (final Architecture architecture in codeAsset.os.architectures) - codeAsset.copyWith(architecture: architecture), - ]; -} - extension OSArchitectures on OS { Set get architectures => _osTargets[this]!; } @@ -1070,3 +924,14 @@ const Map> _osTargets = >{ Architecture.x64, }, }; + +build_info.BuildMode _getBuildMode(Map environmentDefines, bool isFlutterTester) { + if (isFlutterTester) { + return build_info.BuildMode.debug; + } + final String? environmentBuildMode = environmentDefines[build_info.kBuildMode]; + if (environmentBuildMode == null) { + throw MissingDefineException(build_info.kBuildMode, 'native_assets'); + } + return build_info.BuildMode.fromCliName(environmentBuildMode); +} diff --git a/packages/flutter_tools/lib/src/isolated/native_assets/test/native_assets.dart b/packages/flutter_tools/lib/src/isolated/native_assets/test/native_assets.dart index 423c297670b..ea952d31bf0 100644 --- a/packages/flutter_tools/lib/src/isolated/native_assets/test/native_assets.dart +++ b/packages/flutter_tools/lib/src/isolated/native_assets/test/native_assets.dart @@ -50,13 +50,31 @@ Future testCompilerBuildNativeAssets(BuildInfo buildInfo) async { ); return null; } - final (_, Uri nativeAssetsYaml) = await runFlutterSpecificDartBuild( - environmentDefines: { - kBuildMode: buildInfo.mode.cliName, - }, + + // Only `flutter test` uses the + // `build/native_assets//native_assets.json` file which uses absolute + // paths to the shared libraries. + final OS targetOS = getNativeOSFromTargetPlatform(TargetPlatform.tester); + final Uri buildUri = nativeAssetsBuildUri(projectUri, targetOS); + final Uri nativeAssetsFileUri = buildUri.resolve('native_assets.json'); + + final Map environmentDefines = { + kBuildMode: buildInfo.mode.cliName, + }; + + // First perform the dart build. + final DartBuildResult dartBuildResult = await runFlutterSpecificDartBuild( + environmentDefines: environmentDefines, buildRunner: buildRunner, targetPlatform: TargetPlatform.tester, projectUri: projectUri, fileSystem: globals.fs); - return nativeAssetsYaml; + + // Then "install" the code assets so they can be used at runtime. + await installCodeAssets(dartBuildResult: dartBuildResult, environmentDefines: environmentDefines, + targetPlatform: TargetPlatform.tester, projectUri: projectUri, fileSystem: globals.fs, + nativeAssetsFileUri: nativeAssetsFileUri); + assert(await globals.fs.file(nativeAssetsFileUri).exists()); + + return nativeAssetsFileUri; } diff --git a/packages/flutter_tools/lib/src/isolated/resident_web_runner.dart b/packages/flutter_tools/lib/src/isolated/resident_web_runner.dart index 40473a060df..ad5a5f23546 100644 --- a/packages/flutter_tools/lib/src/isolated/resident_web_runner.dart +++ b/packages/flutter_tools/lib/src/isolated/resident_web_runner.dart @@ -57,7 +57,6 @@ class DwdsWebRunnerFactory extends WebRunnerFactory { required SystemClock systemClock, required Usage usage, required Analytics analytics, - required bool useImplicitPubspecResolution, bool machine = false, }) { return ResidentWebRunner( @@ -73,7 +72,6 @@ class DwdsWebRunnerFactory extends WebRunnerFactory { systemClock: systemClock, fileSystem: fileSystem, logger: logger, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); } } @@ -89,7 +87,6 @@ class ResidentWebRunner extends ResidentRunner { bool stayResident = true, bool machine = false, required this.flutterProject, - required bool useImplicitPubspecResolution, required DebuggingOptions debuggingOptions, required FileSystem fileSystem, required Logger logger, @@ -105,7 +102,6 @@ class ResidentWebRunner extends ResidentRunner { _usage = usage, _analytics = analytics, _urlTunneller = urlTunneller, - _useImplicitPubspecResolution = useImplicitPubspecResolution, super( [device], target: target ?? fileSystem.path.join('lib', 'main.dart'), @@ -113,7 +109,6 @@ class ResidentWebRunner extends ResidentRunner { stayResident: stayResident, machine: machine, devtoolsHandler: devtoolsHandler, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); final FileSystem _fileSystem; @@ -122,7 +117,6 @@ class ResidentWebRunner extends ResidentRunner { final Usage _usage; final Analytics _analytics; final UrlTunneller? _urlTunneller; - final bool _useImplicitPubspecResolution; @override Logger get logger => _logger; @@ -351,7 +345,6 @@ Please provide a valid TCP port (an integer between 0 and 65535, inclusive). flutterVersion: globals.flutterVersion, usage: globals.flutterUsage, analytics: globals.analytics, - useImplicitPubspecResolution: _useImplicitPubspecResolution, ); await webBuilder.buildWeb( flutterProject, @@ -448,7 +441,6 @@ Please provide a valid TCP port (an integer between 0 and 65535, inclusive). flutterVersion: globals.flutterVersion, usage: globals.flutterUsage, analytics: globals.analytics, - useImplicitPubspecResolution: _useImplicitPubspecResolution, ); await webBuilder.buildWeb( flutterProject, diff --git a/packages/flutter_tools/lib/src/linux/build_linux.dart b/packages/flutter_tools/lib/src/linux/build_linux.dart index 8f9f1141fb8..882586b217d 100644 --- a/packages/flutter_tools/lib/src/linux/build_linux.dart +++ b/packages/flutter_tools/lib/src/linux/build_linux.dart @@ -124,11 +124,9 @@ Future buildLinux( 'A summary of your Linux bundle analysis can be found at: ${outputFile.path}', ); - // DevTools expects a file path relative to the .flutter-devtools/ dir. - final String relativeAppSizePath = outputFile.path.split('.flutter-devtools/').last.trim(); logger.printStatus( '\nTo analyze your app size in Dart DevTools, run the following command:\n' - 'dart devtools --appSizeBase=$relativeAppSizePath' + 'dart devtools --appSizeBase=${outputFile.path}' ); } } diff --git a/packages/flutter_tools/lib/src/localizations/gen_l10n.dart b/packages/flutter_tools/lib/src/localizations/gen_l10n.dart index 781602346f9..c298bf9fed9 100644 --- a/packages/flutter_tools/lib/src/localizations/gen_l10n.dart +++ b/packages/flutter_tools/lib/src/localizations/gen_l10n.dart @@ -123,23 +123,36 @@ String _syntheticL10nPackagePath(FileSystem fileSystem) => fileSystem.path.join( // For example, if placeholders are used for plurals and no type was specified, then the type will // automatically set to 'num'. Similarly, if such placeholders are used for selects, then the type // will be set to 'String'. For such placeholders that are used for both, we should throw an error. -List generateMethodParameters(Message message, bool useNamedParameters) { - return message.placeholders.values.map((Placeholder placeholder) { +List generateMethodParameters(Message message, LocaleInfo? locale, bool useNamedParameters) { + + // Check the compatibility of template placeholders and locale placeholders. + final Map? localePlaceholders = message.localePlaceholders[locale]; + + return message.templatePlaceholders.entries.map((MapEntry e) { + final Placeholder placeholder = e.value; + final Placeholder? localePlaceholder = localePlaceholders?[e.key]; + if (localePlaceholder != null && placeholder.type != localePlaceholder.type) { + throw L10nException( + 'The placeholder, ${placeholder.name}, has its "type" resource attribute set to ' + 'the "${localePlaceholder.type}" type in locale "$locale", but it is "${placeholder.type}" ' + 'in the template placeholder. For compatibility with template placeholder, change ' + 'the "type" attribute to "${placeholder.type}".'); + } return '${useNamedParameters ? 'required ' : ''}${placeholder.type} ${placeholder.name}'; }).toList(); } // Similar to above, but is used for passing arguments into helper functions. List generateMethodArguments(Message message) { - return message.placeholders.values.map((Placeholder placeholder) => placeholder.name).toList(); + return message.templatePlaceholders.values.map((Placeholder placeholder) => placeholder.name).toList(); } -String generateDateFormattingLogic(Message message) { - if (message.placeholders.isEmpty || !message.placeholdersRequireFormatting) { +String generateDateFormattingLogic(Message message, LocaleInfo locale) { + if (message.templatePlaceholders.isEmpty) { return '@(none)'; } - final Iterable formatStatements = message.placeholders.values + final Iterable formatStatements = message.getPlaceholders(locale) .where((Placeholder placeholder) => placeholder.requiresDateFormatting) .map((Placeholder placeholder) { final String? placeholderFormat = placeholder.format; @@ -156,6 +169,16 @@ String generateDateFormattingLogic(Message message) { final bool? isCustomDateFormat = placeholder.isCustomDateFormat; if (!placeholder.hasValidDateFormat && (isCustomDateFormat == null || !isCustomDateFormat)) { + if (placeholder.dateFormatParts.length > 1) { + throw L10nException( + 'Date format "$placeholderFormat" for placeholder ' + '${placeholder.name} contains at least one invalid date format. ' + 'Ensure all date formats joined by a "+" character have ' + 'a corresponding DateFormat constructor.\n Check the intl ' + "library's DateFormat class constructors for allowed date formats." + ); + } + throw L10nException( 'Date format "$placeholderFormat" for placeholder ' '${placeholder.name} does not have a corresponding DateFormat ' @@ -165,9 +188,19 @@ String generateDateFormattingLogic(Message message) { ); } if (placeholder.hasValidDateFormat) { + // The first format is the main format, and the rest are added formats. + final List formatParts = placeholder.dateFormatParts; + final String mainFormat = formatParts.first; + final List addedFormats = formatParts.skip(1).toList(); + + final String addedFormatsString = addedFormats.map((String addFormat) { + return dateFormatAddFormatTemplate.replaceAll('@(format)', addFormat); + }).join(); + return dateFormatTemplate .replaceAll('@(placeholder)', placeholder.name) - .replaceAll('@(format)', placeholderFormat); + .replaceAll('@(format)', mainFormat) + .replaceAll('@(addedFormats)', addedFormatsString); } return dateFormatCustomTemplate .replaceAll('@(placeholder)', placeholder.name) @@ -177,12 +210,12 @@ String generateDateFormattingLogic(Message message) { return formatStatements.isEmpty ? '@(none)' : formatStatements.join(); } -String generateNumberFormattingLogic(Message message) { - if (message.placeholders.isEmpty || !message.placeholdersRequireFormatting) { +String generateNumberFormattingLogic(Message message, LocaleInfo locale) { + if (message.templatePlaceholders.isEmpty) { return '@(none)'; } - final Iterable formatStatements = message.placeholders.values + final Iterable formatStatements = message.getPlaceholders(locale) .where((Placeholder placeholder) => placeholder.requiresNumFormatting) .map((Placeholder placeholder) { final String? placeholderFormat = placeholder.format; @@ -242,12 +275,12 @@ String generateBaseClassMethod(Message message, LocaleInfo? templateArbLocale, b /// In $templateArbLocale, this message translates to: /// **'${generateString(message.value)}'**'''; - if (message.placeholders.isNotEmpty) { + if (message.templatePlaceholders.isNotEmpty) { return (useNamedParameters ? baseClassMethodWithNamedParameterTemplate : baseClassMethodTemplate) .replaceAll('@(comment)', comment) .replaceAll('@(templateLocaleTranslationComment)', templateLocaleTranslationComment) .replaceAll('@(name)', message.resourceId) - .replaceAll('@(parameters)', generateMethodParameters(message, useNamedParameters).join(', ')); + .replaceAll('@(parameters)', generateMethodParameters(message, null, useNamedParameters).join(', ')); } return baseClassGetterTemplate .replaceAll('@(comment)', comment) @@ -610,10 +643,6 @@ class LocalizationsGenerator { /// ['es', 'en'] is passed in, the 'es' locale will take priority over 'en'. final List preferredSupportedLocales; - // Whether we need to import intl or not. This flag is updated after parsing - // all of the messages. - bool requiresIntlImport = false; - // Whether we want to use escaping for ICU messages. bool useEscaping = false; @@ -993,8 +1022,7 @@ class LocalizationsGenerator { .replaceAll('@(fileName)', fileName) .replaceAll('@(class)', '$className${locale.camelCase()}') .replaceAll('@(localeName)', locale.toString()) - .replaceAll('@(methods)', methods.join('\n\n')) - .replaceAll('@(requiresIntlImport)', requiresIntlImport ? "import 'package:intl/intl.dart' as intl;\n\n" : ''); + .replaceAll('@(methods)', methods.join('\n\n')); } String _generateSubclass( @@ -1143,7 +1171,6 @@ class LocalizationsGenerator { .replaceAll('@(messageClassImports)', sortedClassImports.join('\n')) .replaceAll('@(delegateClass)', delegateClass) .replaceAll('@(requiresFoundationImport)', useDeferredLoading ? '' : "import 'package:flutter/foundation.dart';") - .replaceAll('@(requiresIntlImport)', requiresIntlImport ? "import 'package:intl/intl.dart' as intl;" : '') .replaceAll('@(canBeNullable)', usesNullableGetter ? '?' : '') .replaceAll('@(needsNullCheck)', usesNullableGetter ? '' : '!') // Removes all trailing whitespace from the generated file. @@ -1154,15 +1181,10 @@ class LocalizationsGenerator { String _generateMethod(Message message, LocaleInfo locale) { try { - // Determine if we must import intl for date or number formatting. - if (message.placeholdersRequireFormatting) { - requiresIntlImport = true; - } - final String translationForMessage = message.messages[locale]!; final Node node = message.parsedMessages[locale]!; // If the placeholders list is empty, then return a getter method. - if (message.placeholders.isEmpty) { + if (message.templatePlaceholders.isEmpty) { // Use the parsed translation to handle escaping with the same behavior. return getterTemplate .replaceAll('@(name)', message.resourceId) @@ -1196,14 +1218,13 @@ class LocalizationsGenerator { case ST.placeholderExpr: assert(node.children[1].type == ST.identifier); final String identifier = node.children[1].value!; - final Placeholder placeholder = message.placeholders[identifier]!; + final Placeholder placeholder = message.localePlaceholders[locale]?[identifier] ?? message.templatePlaceholders[identifier]!; if (placeholder.requiresFormatting) { return '\$${node.children[1].value}String'; } return '\$${node.children[1].value}'; case ST.pluralExpr: - requiresIntlImport = true; final Map pluralLogicArgs = {}; // Recall that pluralExpr are of the form // pluralExpr := "{" ID "," "plural" "," pluralParts "}" @@ -1259,7 +1280,6 @@ The plural cases must be one of "=0", "=1", "=2", "zero", "one", "two", "few", " return '\$$tempVarName'; case ST.selectExpr: - requiresIntlImport = true; // Recall that pluralExpr are of the form // pluralExpr := "{" ID "," "plural" "," pluralParts "}" assert(node.children[1].type == ST.identifier); @@ -1284,7 +1304,6 @@ The plural cases must be one of "=0", "=1", "=2", "zero", "one", "two", "few", " ); return '\$$tempVarName'; case ST.argumentExpr: - requiresIntlImport = true; assert(node.children[1].type == ST.identifier); assert(node.children[3].type == ST.argType); assert(node.children[7].type == ST.identifier); @@ -1320,9 +1339,9 @@ The plural cases must be one of "=0", "=1", "=2", "zero", "one", "two", "few", " final String tempVarLines = tempVariables.isEmpty ? '' : '${tempVariables.join('\n')}\n'; return (useNamedParameters ? methodWithNamedParameterTemplate : methodTemplate) .replaceAll('@(name)', message.resourceId) - .replaceAll('@(parameters)', generateMethodParameters(message, useNamedParameters).join(', ')) - .replaceAll('@(dateFormatting)', generateDateFormattingLogic(message)) - .replaceAll('@(numberFormatting)', generateNumberFormattingLogic(message)) + .replaceAll('@(parameters)', generateMethodParameters(message, locale, useNamedParameters).join(', ')) + .replaceAll('@(dateFormatting)', generateDateFormattingLogic(message, locale)) + .replaceAll('@(numberFormatting)', generateNumberFormattingLogic(message, locale)) .replaceAll('@(tempVars)', tempVarLines) .replaceAll('@(message)', messageString) .replaceAll('@(none)\n', ''); diff --git a/packages/flutter_tools/lib/src/localizations/gen_l10n_templates.dart b/packages/flutter_tools/lib/src/localizations/gen_l10n_templates.dart index db87cecf140..5902159c1bc 100644 --- a/packages/flutter_tools/lib/src/localizations/gen_l10n_templates.dart +++ b/packages/flutter_tools/lib/src/localizations/gen_l10n_templates.dart @@ -123,10 +123,12 @@ const String numberFormatNamedTemplate = ''' '''; const String dateFormatTemplate = ''' - final intl.DateFormat @(placeholder)DateFormat = intl.DateFormat.@(format)(localeName); + final intl.DateFormat @(placeholder)DateFormat = intl.DateFormat.@(format)(localeName)@(addedFormats); final String @(placeholder)String = @(placeholder)DateFormat.format(@(placeholder)); '''; +const String dateFormatAddFormatTemplate = '''.add_@(format)()'''; + const String dateFormatCustomTemplate = ''' final intl.DateFormat @(placeholder)DateFormat = intl.DateFormat(@(format), localeName); final String @(placeholder)String = @(placeholder)DateFormat.format(@(placeholder)); @@ -171,7 +173,9 @@ const String dateVariableTemplate = ''' String @(varName) = intl.DateFormat.@(formatType)(localeName).format(@(argument));'''; const String classFileTemplate = ''' -@(header)@(requiresIntlImport)import '@(fileName)'; +@(header)// ignore: unused_import +import 'package:intl/intl.dart' as intl; +import '@(fileName)'; // ignore_for_file: type=lint diff --git a/packages/flutter_tools/lib/src/localizations/gen_l10n_types.dart b/packages/flutter_tools/lib/src/localizations/gen_l10n_types.dart index e6d78c1128c..6cea9c6b6a9 100644 --- a/packages/flutter_tools/lib/src/localizations/gen_l10n_types.dart +++ b/packages/flutter_tools/lib/src/localizations/gen_l10n_types.dart @@ -19,9 +19,9 @@ import 'message_parser.dart'; // DateFormat.yMMMMd("en_US").format(DateTime.utc(1996, 7, 10)) results // in the string "July 10, 1996". // -// Since the tool generates code that uses DateFormat's constructor, it is -// necessary to verify that the constructor exists, or the -// tool will generate code that may cause a compile-time error. +// Since the tool generates code that uses DateFormat's constructor and its +// add_* methods, it is necessary to verify that the constructor/method exists, +// or the tool will generate code that may cause a compile-time error. // // See also: // @@ -72,6 +72,8 @@ const Set validDateFormats = { 's', }; +const String _dateFormatPartsDelimiter = '+'; + // The set of number formats that can be automatically localized. // // The localizations generation tool makes use of the intl library's @@ -252,7 +254,9 @@ class Placeholder { bool get requiresNumFormatting => ['int', 'num', 'double'].contains(type) && format != null; bool get hasValidNumberFormat => _validNumberFormats.contains(format); bool get hasNumberFormatWithParameters => _numberFormatsWithNamedParameters.contains(format); - bool get hasValidDateFormat => validDateFormats.contains(format); + // 'format' can contain a number of date time formats separated by `dateFormatPartsDelimiter`. + List get dateFormatParts => format?.split(_dateFormatPartsDelimiter) ?? []; + bool get hasValidDateFormat => dateFormatParts.every(validDateFormats.contains); static String? _stringAttribute( String resourceId, @@ -347,7 +351,8 @@ class Message { ) : assert(resourceId.isNotEmpty), value = _value(templateBundle.resources, resourceId), description = _description(templateBundle.resources, resourceId, isResourceAttributeRequired), - placeholders = _placeholders(templateBundle.resources, resourceId, isResourceAttributeRequired), + templatePlaceholders = _placeholders(templateBundle.resources, resourceId, isResourceAttributeRequired), + localePlaceholders = >{}, messages = {}, parsedMessages = {} { // Filenames for error handling. @@ -357,9 +362,14 @@ class Message { filenames[bundle.locale] = bundle.file.basename; final String? translation = bundle.translationFor(resourceId); messages[bundle.locale] = translation; + + localePlaceholders[bundle.locale] = templateBundle.locale == bundle.locale + ? templatePlaceholders + : _placeholders(bundle.resources, resourceId, false); + List? validPlaceholders; if (useRelaxedSyntax) { - validPlaceholders = placeholders.entries.map((MapEntry e) => e.key).toList(); + validPlaceholders = templatePlaceholders.entries.map((MapEntry e) => e.key).toList(); } try { parsedMessages[bundle.locale] = translation == null ? null : Parser( @@ -378,7 +388,7 @@ class Message { } } // Infer the placeholders - _inferPlaceholders(filenames); + _inferPlaceholders(); } final String resourceId; @@ -386,13 +396,21 @@ class Message { final String? description; late final Map messages; final Map parsedMessages; - final Map placeholders; + final Map> localePlaceholders; + final Map templatePlaceholders; final bool useEscaping; final bool useRelaxedSyntax; final Logger? logger; bool hadErrors = false; - bool get placeholdersRequireFormatting => placeholders.values.any((Placeholder p) => p.requiresFormatting); + Iterable getPlaceholders(LocaleInfo locale) { + final Map? placeholders = localePlaceholders[locale]; + if (placeholders == null) { + return templatePlaceholders.values; + } + return templatePlaceholders.values + .map((Placeholder templatePlaceholder) => placeholders[templatePlaceholder.name] ?? templatePlaceholder); + } static String _value(Map bundle, String resourceId) { final Object? value = bundle[resourceId]; @@ -488,12 +506,15 @@ class Message { // Using parsed translations, attempt to infer types of placeholders used by plurals and selects. // For undeclared placeholders, create a new placeholder. - void _inferPlaceholders(Map filenames) { + void _inferPlaceholders() { // We keep the undeclared placeholders separate so that we can sort them alphabetically afterwards. final Map undeclaredPlaceholders = {}; // Helper for getting placeholder by name. - Placeholder? getPlaceholder(String name) => placeholders[name] ?? undeclaredPlaceholders[name]; for (final LocaleInfo locale in parsedMessages.keys) { + Placeholder? getPlaceholder(String name) => + localePlaceholders[locale]?[name] ?? + templatePlaceholders[name] ?? + undeclaredPlaceholders[name]; if (parsedMessages[locale] == null) { continue; } @@ -529,7 +550,7 @@ class Message { traversalStack.addAll(node.children); } } - placeholders.addEntries( + templatePlaceholders.addEntries( undeclaredPlaceholders.entries .toList() ..sort((MapEntry p1, MapEntry p2) => p1.key.compareTo(p2.key)) @@ -542,7 +563,7 @@ class Message { || !x && !y && !z; } - for (final Placeholder placeholder in placeholders.values) { + for (final Placeholder placeholder in templatePlaceholders.values) { if (!atMostOneOf(placeholder.isPlural, placeholder.isDateTime, placeholder.isSelect)) { throw L10nException('Placeholder is used as plural/select/datetime in certain languages.'); } else if (placeholder.isPlural) { @@ -618,7 +639,7 @@ class AppResourceBundle { 'The locale specified in @@locale and the arb filename do not match. \n' 'Please make sure that they match, since this prevents any confusion \n' 'with which locale to use. Otherwise, specify the locale in either the \n' - 'filename of the @@locale key only.\n' + 'filename or the @@locale key only.\n' 'Current @@locale value: $localeString\n' 'Current filename extension: $parserLocaleString' ); diff --git a/packages/flutter_tools/lib/src/macos/build_macos.dart b/packages/flutter_tools/lib/src/macos/build_macos.dart index 5b8b186a238..2e9ffbed470 100644 --- a/packages/flutter_tools/lib/src/macos/build_macos.dart +++ b/packages/flutter_tools/lib/src/macos/build_macos.dart @@ -13,7 +13,9 @@ import '../base/terminal.dart'; import '../base/utils.dart'; import '../build_info.dart'; import '../convert.dart'; +import '../features.dart'; import '../globals.dart' as globals; +import '../ios/migrations/metal_api_validation_migration.dart'; import '../ios/xcode_build_settings.dart'; import '../ios/xcodeproj.dart'; import '../migrations/swift_package_manager_gitignore_migration.dart'; @@ -91,17 +93,18 @@ Future buildMacOS({ FlutterApplicationMigration(flutterProject.macos, globals.logger), NSApplicationMainDeprecationMigration(flutterProject.macos, globals.logger), SecureRestorableStateMigration(flutterProject.macos, globals.logger), - if (flutterProject.usesSwiftPackageManager && flutterProject.macos.flutterPluginSwiftPackageManifest.existsSync()) - SwiftPackageManagerIntegrationMigration( - flutterProject.macos, - SupportedPlatform.macos, - buildInfo, - xcodeProjectInterpreter: globals.xcodeProjectInterpreter!, - logger: globals.logger, - fileSystem: globals.fs, - plistParser: globals.plistParser, - ), - SwiftPackageManagerGitignoreMigration(flutterProject, globals.logger), + SwiftPackageManagerIntegrationMigration( + flutterProject.macos, + SupportedPlatform.macos, + buildInfo, + xcodeProjectInterpreter: globals.xcodeProjectInterpreter!, + logger: globals.logger, + fileSystem: globals.fs, + plistParser: globals.plistParser, + features: featureFlags, + ), + SwiftPackageManagerGitignoreMigration(flutterProject, globals.logger), + MetalAPIValidationMigrator.macos(flutterProject.macos, globals.logger), ]; final ProjectMigration migration = ProjectMigration(migrators); @@ -145,7 +148,7 @@ Future buildMacOS({ useMacOSConfig: true, ); - if (flutterProject.usesSwiftPackageManager) { + if (flutterProject.macos.usesSwiftPackageManager) { final String? macOSDeploymentTarget = buildSettings['MACOSX_DEPLOYMENT_TARGET']; if (macOSDeploymentTarget != null) { SwiftPackageManager.updateMinimumDeployment( @@ -300,11 +303,9 @@ Future _writeCodeSizeAnalysis(BuildInfo buildInfo, SizeAnalyzer? sizeAnaly 'A summary of your macOS bundle analysis can be found at: ${outputFile.path}', ); - // DevTools expects a file path relative to the .flutter-devtools/ dir. - final String relativeAppSizePath = outputFile.path.split('.flutter-devtools/').last.trim(); globals.printStatus( '\nTo analyze your app size in Dart DevTools, run the following command:\n' - 'dart devtools --appSizeBase=$relativeAppSizePath' + 'dart devtools --appSizeBase=${outputFile.path}' ); } diff --git a/packages/flutter_tools/lib/src/macos/cocoapod_utils.dart b/packages/flutter_tools/lib/src/macos/cocoapod_utils.dart index fc78aee9917..9226778e6b9 100644 --- a/packages/flutter_tools/lib/src/macos/cocoapod_utils.dart +++ b/packages/flutter_tools/lib/src/macos/cocoapod_utils.dart @@ -22,7 +22,7 @@ Future processPodsIfNeeded( // When using Swift Package Manager, the Podfile may not exist so if there // isn't a Podfile, skip processing pods. - if (project.usesSwiftPackageManager && + if (xcodeProject.usesSwiftPackageManager && !xcodeProject.podfile.existsSync() && !forceCocoaPodsOnly) { return; @@ -38,7 +38,8 @@ Future processPodsIfNeeded( // file being generated. A better long-term fix would be not to have a call to refreshPluginsList // at all, and instead have it implicitly run by the FlutterCommand instead. See // https://github.com/flutter/flutter/issues/157391 for details. - useImplicitPubspecResolution: false, + determineDevDependencies: false, + generateLegacyPlugins: false, ); // If there are no plugins and if the project is a not module with an existing @@ -50,7 +51,7 @@ Future processPodsIfNeeded( // If forcing the use of only CocoaPods, but the project is using Swift // Package Manager, print a warning that CocoaPods will be used. - if (forceCocoaPodsOnly && project.usesSwiftPackageManager) { + if (forceCocoaPodsOnly && xcodeProject.usesSwiftPackageManager) { globals.logger.printWarning( 'Swift Package Manager does not yet support this command. ' 'CocoaPods will be used instead.'); diff --git a/packages/flutter_tools/lib/src/macos/cocoapods.dart b/packages/flutter_tools/lib/src/macos/cocoapods.dart index 1205983bcf4..fd7486fd28e 100644 --- a/packages/flutter_tools/lib/src/macos/cocoapods.dart +++ b/packages/flutter_tools/lib/src/macos/cocoapods.dart @@ -167,7 +167,7 @@ class CocoaPods { }) async { if (!xcodeProject.podfile.existsSync()) { // Swift Package Manager doesn't need Podfile, so don't error. - if (xcodeProject.parent.usesSwiftPackageManager) { + if (xcodeProject.usesSwiftPackageManager) { return false; } throwToolExit('Podfile missing'); @@ -503,7 +503,7 @@ class CocoaPods { } } } else if (stdout.contains('unknown ISA `PBXFileSystemSynchronizedRootGroup`')) { - // CocoaPods must be at least verison 1.16.2 to handle synchronized + // CocoaPods must be at least version 1.16.2 to handle synchronized // groups/folders https://github.com/CocoaPods/CocoaPods/issues/12456 _logger.printError( 'Error: Your Cocoapods might be out-of-date and unable to support synchronized groups/folders. ' diff --git a/packages/flutter_tools/lib/src/macos/darwin_dependency_management.dart b/packages/flutter_tools/lib/src/macos/darwin_dependency_management.dart index af1cebe54ed..a615726aa12 100644 --- a/packages/flutter_tools/lib/src/macos/darwin_dependency_management.dart +++ b/packages/flutter_tools/lib/src/macos/darwin_dependency_management.dart @@ -60,7 +60,7 @@ class DarwinDependencyManagement { final XcodeBasedProject xcodeProject = platform == SupportedPlatform.ios ? _project.ios : _project.macos; - if (_project.usesSwiftPackageManager) { + if (xcodeProject.usesSwiftPackageManager) { await _swiftPackageManager.generatePluginsSwiftPackage( _plugins, platform, @@ -89,12 +89,8 @@ class DarwinDependencyManagement { ); final bool useCocoapods; - if (_project.usesSwiftPackageManager) { - useCocoapods = _usingCocoaPodsPlugin( - pluginCount: totalCount, - swiftPackageCount: swiftPackageCount, - cocoapodCount: podCount, - ); + if (xcodeProject.usesSwiftPackageManager) { + useCocoapods = swiftPackageCount < totalCount; } else { // When Swift Package Manager is not enabled, set up Podfile if plugins // is not empty, regardless of if plugins are CocoaPod compatible. This @@ -112,19 +108,6 @@ class DarwinDependencyManagement { } } - bool _usingCocoaPodsPlugin({ - required int pluginCount, - required int swiftPackageCount, - required int cocoapodCount, - }) { - if (_project.usesSwiftPackageManager) { - if (pluginCount == swiftPackageCount) { - return false; - } - } - return cocoapodCount > 0; - } - /// Returns count of total number of plugins, number of Swift Package Manager /// compatible plugins, and number of CocoaPods compatible plugins. A plugin /// can be both Swift Package Manager and CocoaPods compatible. @@ -178,7 +161,7 @@ class DarwinDependencyManagement { // If not using Swift Package Manager and plugin does not have podspec // but does have a Package.swift, throw an error. Otherwise, it'll error // when it builds. - if (!_project.usesSwiftPackageManager && + if (!xcodeProject.usesSwiftPackageManager && !cocoaPodsCompatible && swiftPackageManagerCompatible) { throwToolExit( @@ -192,7 +175,7 @@ class DarwinDependencyManagement { // Only show warnings to remove CocoaPods if the project is using Swift // Package Manager, has already been migrated to have SPM integration, and // all plugins are Swift Packages. - if (_project.usesSwiftPackageManager && + if (xcodeProject.usesSwiftPackageManager && xcodeProject.flutterPluginSwiftPackageInProjectSettings && pluginCount == swiftPackageCount && swiftPackageCount != 0) { diff --git a/packages/flutter_tools/lib/src/migrations/swift_package_manager_integration_migration.dart b/packages/flutter_tools/lib/src/migrations/swift_package_manager_integration_migration.dart index e3e74239a17..6da2be7d785 100644 --- a/packages/flutter_tools/lib/src/migrations/swift_package_manager_integration_migration.dart +++ b/packages/flutter_tools/lib/src/migrations/swift_package_manager_integration_migration.dart @@ -11,6 +11,7 @@ import '../base/logger.dart'; import '../base/project_migrator.dart'; import '../build_info.dart'; import '../convert.dart'; +import '../features.dart'; import '../ios/plist_parser.dart'; import '../ios/xcodeproj.dart'; import '../project.dart'; @@ -26,6 +27,7 @@ class SwiftPackageManagerIntegrationMigration extends ProjectMigrator { required Logger logger, required FileSystem fileSystem, required PlistParser plistParser, + required FeatureFlags features, }) : _xcodeProject = project, _platform = platform, _buildInfo = buildInfo, @@ -33,6 +35,7 @@ class SwiftPackageManagerIntegrationMigration extends ProjectMigrator { _xcodeProjectInterpreter = xcodeProjectInterpreter, _fileSystem = fileSystem, _plistParser = plistParser, + _features = features, super(logger); final XcodeBasedProject _xcodeProject; @@ -42,27 +45,28 @@ class SwiftPackageManagerIntegrationMigration extends ProjectMigrator { final FileSystem _fileSystem; final File _xcodeProjectInfoFile; final PlistParser _plistParser; + final FeatureFlags _features; /// New identifier for FlutterGeneratedPluginSwiftPackage PBXBuildFile. static const String _flutterPluginsSwiftPackageBuildFileIdentifier = '78A318202AECB46A00862997'; /// New identifier for FlutterGeneratedPluginSwiftPackage XCLocalSwiftPackageReference. - static const String _localFlutterPluginsSwiftPackageReferenceIdentifer = '781AD8BC2B33823900A9FFBB'; + static const String _localFlutterPluginsSwiftPackageReferenceIdentifier = '781AD8BC2B33823900A9FFBB'; /// New identifier for FlutterGeneratedPluginSwiftPackage XCSwiftPackageProductDependency. - static const String _flutterPluginsSwiftPackageProductDependencyIdentifer = '78A3181F2AECB46A00862997'; + static const String _flutterPluginsSwiftPackageProductDependencyIdentifier = '78A3181F2AECB46A00862997'; /// Existing iOS identifier for Runner PBXFrameworksBuildPhase. - static const String _iosRunnerFrameworksBuildPhaseIdentifer = '97C146EB1CF9000F007C117D'; + static const String _iosRunnerFrameworksBuildPhaseIdentifier = '97C146EB1CF9000F007C117D'; /// Existing macOS identifier for Runner PBXFrameworksBuildPhase. - static const String _macosRunnerFrameworksBuildPhaseIdentifer = '33CC10EA2044A3C60003C045'; + static const String _macosRunnerFrameworksBuildPhaseIdentifier = '33CC10EA2044A3C60003C045'; /// Existing iOS identifier for Runner PBXNativeTarget. - static const String _iosRunnerNativeTargetIdentifer = '97C146ED1CF9000F007C117D'; + static const String _iosRunnerNativeTargetIdentifier = '97C146ED1CF9000F007C117D'; /// Existing macOS identifier for Runner PBXNativeTarget. - static const String _macosRunnerNativeTargetIdentifer = '33CC10EC2044A3C60003C045'; + static const String _macosRunnerNativeTargetIdentifier = '33CC10EC2044A3C60003C045'; /// Existing iOS identifier for Runner PBXProject. static const String _iosProjectIdentifier = '97C146E61CF9000F007C117D'; @@ -74,16 +78,16 @@ class SwiftPackageManagerIntegrationMigration extends ProjectMigrator { .directory(_xcodeProjectInfoFile.parent) .childFile('project.pbxproj.backup'); - String get _runnerFrameworksBuildPhaseIdentifer { + String get _runnerFrameworksBuildPhaseIdentifier { return _platform == SupportedPlatform.ios - ? _iosRunnerFrameworksBuildPhaseIdentifer - : _macosRunnerFrameworksBuildPhaseIdentifer; + ? _iosRunnerFrameworksBuildPhaseIdentifier + : _macosRunnerFrameworksBuildPhaseIdentifier; } - String get _runnerNativeTargetIdentifer { + String get _runnerNativeTargetIdentifier { return _platform == SupportedPlatform.ios - ? _iosRunnerNativeTargetIdentifer - : _macosRunnerNativeTargetIdentifer; + ? _iosRunnerNativeTargetIdentifier + : _macosRunnerNativeTargetIdentifier; } String get _projectIdentifier { @@ -107,6 +111,23 @@ class SwiftPackageManagerIntegrationMigration extends ProjectMigrator { /// will revert any changes made and throw an error. @override Future migrate() async { + if (!_features.isSwiftPackageManagerEnabled) { + logger.printTrace( + 'The Swift Package Manager feature is off. ' + 'Skipping the migration that adds Swift Package Manager integration...', + ); + return; + } + + if (!_xcodeProject.flutterPluginSwiftPackageManifest.existsSync()) { + logger.printTrace( + 'The tool did not generate a Swift package. ' + "This can happen if the project doesn't have any plugins. " + 'Skipping the migration that adds Swift Package Manager integration...', + ); + return; + } + Status? migrationStatus; SchemeInfo? schemeInfo; try { @@ -234,7 +255,7 @@ class SwiftPackageManagerIntegrationMigration extends ProjectMigrator { // final List schemeLines = LineSplitter.split(schemeContent).toList(); final int index = schemeLines.indexWhere((String line) => - line.contains('BlueprintIdentifier = "$_runnerNativeTargetIdentifer"'), + line.contains('BlueprintIdentifier = "$_runnerNativeTargetIdentifier"'), ); if (index == -1 || index + 3 >= schemeLines.length) { throw Exception( @@ -276,7 +297,7 @@ class SwiftPackageManagerIntegrationMigration extends ProjectMigrator { - phase.identifier == _runnerFrameworksBuildPhaseIdentifer && + phase.identifier == _runnerFrameworksBuildPhaseIdentifier && phase.files != null && phase.files!.contains(_flutterPluginsSwiftPackageBuildFileIdentifier)) .toList() @@ -472,7 +493,7 @@ $newContent // Find index where Frameworks Build Phase for the Runner target begins. final int runnerFrameworksPhaseStartIndex = lines.indexWhere( (String line) => line.trim().startsWith( - '$_runnerFrameworksBuildPhaseIdentifer /* Frameworks */ = {', + '$_runnerFrameworksBuildPhaseIdentifier /* Frameworks */ = {', ), startSectionIndex, ); @@ -488,7 +509,7 @@ $newContent final ParsedProjectFrameworksBuildPhase? runnerFrameworksPhase = projectInfo .frameworksBuildPhases .where((ParsedProjectFrameworksBuildPhase phase) => - phase.identifier == _runnerFrameworksBuildPhaseIdentifer) + phase.identifier == _runnerFrameworksBuildPhaseIdentifier) .toList() .firstOrNull; if (runnerFrameworksPhase == null) { @@ -529,10 +550,10 @@ $newContent }) { final bool migrated = projectInfo.nativeTargets .where((ParsedNativeTarget target) => - target.identifier == _runnerNativeTargetIdentifer && + target.identifier == _runnerNativeTargetIdentifier && target.packageProductDependencies != null && target.packageProductDependencies! - .contains(_flutterPluginsSwiftPackageProductDependencyIdentifer)) + .contains(_flutterPluginsSwiftPackageProductDependencyIdentifier)) .toList() .isNotEmpty; if (logErrorIfNotMigrated && !migrated) { @@ -555,7 +576,7 @@ $newContent // Find index where Native Target for the Runner target begins. final ParsedNativeTarget? runnerNativeTarget = projectInfo.nativeTargets .where((ParsedNativeTarget target) => - target.identifier == _runnerNativeTargetIdentifer) + target.identifier == _runnerNativeTargetIdentifier) .firstOrNull; if (runnerNativeTarget == null) { throw Exception( @@ -563,8 +584,8 @@ $newContent ); } final String subsectionLineStart = runnerNativeTarget.name != null - ? '$_runnerNativeTargetIdentifer /* ${runnerNativeTarget.name} */ = {' - : _runnerNativeTargetIdentifer; + ? '$_runnerNativeTargetIdentifier /* ${runnerNativeTarget.name} */ = {' + : _runnerNativeTargetIdentifier; final int runnerNativeTargetStartIndex = lines.indexWhere( (String line) => line.trim().startsWith(subsectionLineStart), startSectionIndex, @@ -580,7 +601,7 @@ $newContent // If packageProductDependencies is null, the packageProductDependencies field is missing and must be added. const List newContent = [ ' packageProductDependencies = (', - ' $_flutterPluginsSwiftPackageProductDependencyIdentifer /* FlutterGeneratedPluginSwiftPackage */,', + ' $_flutterPluginsSwiftPackageProductDependencyIdentifier /* FlutterGeneratedPluginSwiftPackage */,', ' );', ]; lines.insertAll(runnerNativeTargetStartIndex + 1, newContent); @@ -596,7 +617,7 @@ $newContent ); } const String newContent = - ' $_flutterPluginsSwiftPackageProductDependencyIdentifer /* FlutterGeneratedPluginSwiftPackage */,'; + ' $_flutterPluginsSwiftPackageProductDependencyIdentifier /* FlutterGeneratedPluginSwiftPackage */,'; lines.insert(packageProductDependenciesIndex + 1, newContent); } return lines; @@ -611,7 +632,7 @@ $newContent target.identifier == _projectIdentifier && target.packageReferences != null && target.packageReferences! - .contains(_localFlutterPluginsSwiftPackageReferenceIdentifer)) + .contains(_localFlutterPluginsSwiftPackageReferenceIdentifier)) .toList() .isNotEmpty; if (logErrorIfNotMigrated && !migrated) { @@ -660,7 +681,7 @@ $newContent // If packageReferences is null, the packageReferences field is missing and must be added. const List newContent = [ ' packageReferences = (', - ' $_localFlutterPluginsSwiftPackageReferenceIdentifer /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */,', + ' $_localFlutterPluginsSwiftPackageReferenceIdentifier /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */,', ' );', ]; lines.insertAll(projectStartIndex + 1, newContent); @@ -676,7 +697,7 @@ $newContent ); } const String newContent = - ' $_localFlutterPluginsSwiftPackageReferenceIdentifer /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */,'; + ' $_localFlutterPluginsSwiftPackageReferenceIdentifier /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */,'; lines.insert(packageReferencesIndex + 1, newContent); } return lines; @@ -687,7 +708,7 @@ $newContent bool logErrorIfNotMigrated = false, }) { final bool migrated = projectInfo.localSwiftPackageProductDependencies - .contains(_localFlutterPluginsSwiftPackageReferenceIdentifer); + .contains(_localFlutterPluginsSwiftPackageReferenceIdentifier); if (logErrorIfNotMigrated && !migrated) { logger.printError('XCLocalSwiftPackageReference was not migrated or was migrated incorrectly.'); } @@ -713,7 +734,7 @@ $newContent // There isn't a XCLocalSwiftPackageReference section yet, so add it final List newContent = [ '/* Begin XCLocalSwiftPackageReference section */', - ' $_localFlutterPluginsSwiftPackageReferenceIdentifer /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = {', + ' $_localFlutterPluginsSwiftPackageReferenceIdentifier /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = {', ' isa = XCLocalSwiftPackageReference;', ' relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage;', ' };', @@ -731,7 +752,7 @@ $newContent } final List newContent = [ - ' $_localFlutterPluginsSwiftPackageReferenceIdentifer /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = {', + ' $_localFlutterPluginsSwiftPackageReferenceIdentifier /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = {', ' isa = XCLocalSwiftPackageReference;', ' relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage;', ' };', @@ -747,7 +768,7 @@ $newContent bool logErrorIfNotMigrated = false, }) { final bool migrated = projectInfo.swiftPackageProductDependencies - .contains(_flutterPluginsSwiftPackageProductDependencyIdentifer); + .contains(_flutterPluginsSwiftPackageProductDependencyIdentifier); if (logErrorIfNotMigrated && !migrated) { logger.printError('XCSwiftPackageProductDependency was not migrated or was migrated incorrectly.'); } @@ -773,7 +794,7 @@ $newContent // There isn't a XCSwiftPackageProductDependency section yet, so add it final List newContent = [ '/* Begin XCSwiftPackageProductDependency section */', - ' $_flutterPluginsSwiftPackageProductDependencyIdentifer /* FlutterGeneratedPluginSwiftPackage */ = {', + ' $_flutterPluginsSwiftPackageProductDependencyIdentifier /* FlutterGeneratedPluginSwiftPackage */ = {', ' isa = XCSwiftPackageProductDependency;', ' productName = FlutterGeneratedPluginSwiftPackage;', ' };', @@ -791,7 +812,7 @@ $newContent } final List newContent = [ - ' $_flutterPluginsSwiftPackageProductDependencyIdentifer /* FlutterGeneratedPluginSwiftPackage */ = {', + ' $_flutterPluginsSwiftPackageProductDependencyIdentifier /* FlutterGeneratedPluginSwiftPackage */ = {', ' isa = XCSwiftPackageProductDependency;', ' productName = FlutterGeneratedPluginSwiftPackage;', ' };', diff --git a/packages/flutter_tools/lib/src/preview_device.dart b/packages/flutter_tools/lib/src/preview_device.dart index 71e71122da6..2577a29e607 100644 --- a/packages/flutter_tools/lib/src/preview_device.dart +++ b/packages/flutter_tools/lib/src/preview_device.dart @@ -37,14 +37,12 @@ class PreviewDeviceDiscovery extends PollingDeviceDiscovery { required Logger logger, required ProcessManager processManager, required FeatureFlags featureFlags, - required bool useImplicitPubspecResolution, }) : _artifacts = artifacts, _logger = logger, _processManager = processManager, _fileSystem = fileSystem, _platform = platform, _features = featureFlags, - _useImplicitPubspecResolution = useImplicitPubspecResolution, super('Flutter preview device'); final Platform _platform; @@ -53,7 +51,6 @@ class PreviewDeviceDiscovery extends PollingDeviceDiscovery { final ProcessManager _processManager; final FileSystem _fileSystem; final FeatureFlags _features; - final bool _useImplicitPubspecResolution; @override bool get canListAnything => _platform.isWindows; @@ -78,7 +75,6 @@ class PreviewDeviceDiscovery extends PollingDeviceDiscovery { logger: _logger, processManager: _processManager, previewBinary: previewBinary, - useImplicitPubspecResolution: _useImplicitPubspecResolution, ); return [ if (_features.isPreviewDeviceEnabled) @@ -103,7 +99,6 @@ class PreviewDevice extends Device { required FileSystem fileSystem, required Artifacts artifacts, required File previewBinary, - required bool useImplicitPubspecResolution, @visibleForTesting BundleBuilderFactory builderFactory = _defaultBundleBuilder, }) : _previewBinary = previewBinary, _processManager = processManager, @@ -111,7 +106,6 @@ class PreviewDevice extends Device { _fileSystem = fileSystem, _bundleBuilderFactory = builderFactory, _artifacts = artifacts, - _useImplicitPubspecResolution = useImplicitPubspecResolution, super('preview', ephemeral: false, category: Category.desktop, platformType: PlatformType.windowsPreview); final ProcessManager _processManager; @@ -120,7 +114,6 @@ class PreviewDevice extends Device { final BundleBuilderFactory _bundleBuilderFactory; final Artifacts _artifacts; final File _previewBinary; - final bool _useImplicitPubspecResolution; /// The set of plugins that are allowed to be used by Preview users. /// @@ -191,7 +184,6 @@ class PreviewDevice extends Device { mainPath: mainPath, platform: TargetPlatform.windows_x64, assetDirPath: getAssetBuildDirectory(), - useImplicitPubspecResolution: _useImplicitPubspecResolution, ); copyDirectory(_fileSystem.directory( getAssetBuildDirectory()), diff --git a/packages/flutter_tools/lib/src/project.dart b/packages/flutter_tools/lib/src/project.dart index d1462587a3e..6d5a6aaa24b 100644 --- a/packages/flutter_tools/lib/src/project.dart +++ b/packages/flutter_tools/lib/src/project.dart @@ -5,6 +5,7 @@ import 'package:meta/meta.dart'; import 'package:xml/xml.dart'; import 'package:yaml/yaml.dart'; +import 'package:yaml_edit/yaml_edit.dart'; import '../src/convert.dart'; import 'android/android_builder.dart'; @@ -17,11 +18,11 @@ import 'base/utils.dart'; import 'base/version.dart'; import 'bundle.dart' as bundle; import 'cmake_project.dart'; +import 'dart/package_map.dart'; import 'features.dart'; import 'flutter_manifest.dart'; import 'flutter_plugins.dart'; import 'globals.dart' as globals; -import 'macos/xcode.dart'; import 'platform_plugins.dart'; import 'project_validator_result.dart'; import 'template.dart'; @@ -94,7 +95,7 @@ class FlutterProjectFactory { /// cached. class FlutterProject { @visibleForTesting - FlutterProject(this.directory, this.manifest, this._exampleManifest); + FlutterProject(this.directory, this._manifest, this._exampleManifest); /// Returns a [FlutterProject] view of the given directory or a ToolExit error, /// if `pubspec.yaml` or `example/pubspec.yaml` is invalid. @@ -131,7 +132,8 @@ class FlutterProject { Directory get buildDirectory => directory.childDirectory('build'); /// The manifest of this project. - final FlutterManifest manifest; + FlutterManifest get manifest => _manifest; + late FlutterManifest _manifest; /// The manifest of the example sub-project of this project. final FlutterManifest _exampleManifest; @@ -227,9 +229,15 @@ class FlutterProject { /// The `.gitignore` file of this project. File get gitignoreFile => directory.childFile('.gitignore'); + File get packageConfig => findPackageConfigFileOrDefault(directory); + /// The `.dart-tool` directory of this project. Directory get dartTool => directory.childDirectory('.dart_tool'); + /// The location of the generated scaffolding project for hosting widget + /// previews from this project. + Directory get widgetPreviewScaffold => dartTool.childDirectory('widget_preview_scaffold'); + /// The directory containing the generated code for this project. Directory get generated => directory .absolute @@ -250,6 +258,12 @@ class FlutterProject { FlutterManifest.empty(logger: globals.logger), ); + /// The generated scaffolding project for hosting widget previews from this + /// project. + late final FlutterProject widgetPreviewScaffoldProject = FlutterProject.fromDirectory( + widgetPreviewScaffold, + ); + /// True if this project is a Flutter module project. bool get isModule => manifest.isModule; @@ -262,24 +276,6 @@ class FlutterProject { /// True if this project has an example application. bool get hasExampleApp => _exampleDirectory(directory).existsSync(); - /// True if this project doesn't have Swift Package Manager disabled in the - /// pubspec, has either an iOS or macOS platform implementation, is not a - /// module project, Xcode is 15 or greater, and the Swift Package Manager - /// feature is enabled. - bool get usesSwiftPackageManager { - if (!manifest.disabledSwiftPackageManager && - (ios.existsSync() || macos.existsSync()) && - !isModule) { - final Xcode? xcode = globals.xcode; - final Version? xcodeVersion = xcode?.currentVersion; - if (xcodeVersion == null || xcodeVersion.major < 15) { - return false; - } - return featureFlags.isSwiftPackageManagerEnabled; - } - return false; - } - /// Returns a list of platform names that are supported by the project. List getSupportedPlatforms({bool includeRoot = false}) { return [ @@ -329,6 +325,16 @@ class FlutterProject { return manifest; } + /// Replaces the content of [pubspecFile] with the contents of [updated] and + /// sets [manifest] to the [updated] manifest. + void replacePubspec(FlutterManifest updated) { + final YamlMap updatedPubspecContents = updated.toYaml(); + final YamlEditor editor = YamlEditor(''); + editor.update(const [], updatedPubspecContents); + pubspecFile.writeAsStringSync(editor.toString()); + _manifest = updated; + } + /// Reapplies template files and regenerates project files and plugin /// registrants for app and module projects only. /// @@ -340,7 +346,6 @@ class FlutterProject { Future regeneratePlatformSpecificTooling({ DeprecationBehavior deprecationBehavior = DeprecationBehavior.none, Iterable? allowedPlugins, - required bool useImplicitPubspecResolution, }) async { return ensureReadyForPlatformSpecificTooling( androidPlatform: android.existsSync(), @@ -353,7 +358,6 @@ class FlutterProject { webPlatform: featureFlags.isWebEnabled && web.existsSync(), deprecationBehavior: deprecationBehavior, allowedPlugins: allowedPlugins, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); } @@ -368,7 +372,6 @@ class FlutterProject { bool webPlatform = false, DeprecationBehavior deprecationBehavior = DeprecationBehavior.none, Iterable? allowedPlugins, - required bool useImplicitPubspecResolution, }) async { if (!directory.existsSync() || isPlugin) { return; @@ -377,7 +380,6 @@ class FlutterProject { this, iosPlatform: iosPlatform, macOSPlatform: macOSPlatform, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); if (androidPlatform) { await android.ensureReadyForPlatformSpecificTooling(deprecationBehavior: deprecationBehavior); @@ -405,7 +407,6 @@ class FlutterProject { macOSPlatform: macOSPlatform, windowsPlatform: windowsPlatform, allowedPlugins: allowedPlugins, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); } @@ -889,7 +890,7 @@ $javaGradleCompatUrl } for (final XmlElement metaData in document.findAllElements('meta-data')) { final String? name = metaData.getAttribute('android:name'); - // External code checks for this string to indentify flutter android apps. + // External code checks for this string to identify flutter android apps. // See cl/667760684 as an example. if (name == 'flutterEmbedding') { final String? embeddingVersionString = metaData.getAttribute('android:value'); diff --git a/packages/flutter_tools/lib/src/proxied_devices/devices.dart b/packages/flutter_tools/lib/src/proxied_devices/devices.dart index 4163beb02e7..f66560d66e5 100644 --- a/packages/flutter_tools/lib/src/proxied_devices/devices.dart +++ b/packages/flutter_tools/lib/src/proxied_devices/devices.dart @@ -20,6 +20,7 @@ import '../device_port_forwarder.dart'; import '../device_vm_service_discovery_for_attach.dart'; import '../project.dart'; import '../resident_runner.dart'; +import '../vmservice.dart'; import 'debounce_data_stream.dart'; import 'file_transfer.dart'; @@ -517,6 +518,9 @@ class _ProxiedLogReader extends DeviceLogReader { }); } } + + @override + Future provideVmService(FlutterVmService connectedVmService) async { } } /// A port forwarded by a [ProxiedPortForwarder]. diff --git a/packages/flutter_tools/lib/src/resident_devtools_handler.dart b/packages/flutter_tools/lib/src/resident_devtools_handler.dart index ae5f2b2a840..38e66b64e64 100644 --- a/packages/flutter_tools/lib/src/resident_devtools_handler.dart +++ b/packages/flutter_tools/lib/src/resident_devtools_handler.dart @@ -69,7 +69,6 @@ class FlutterResidentDevtoolsHandler implements ResidentDevtoolsHandler { final ResidentRunner _residentRunner; final Logger _logger; bool _shutdown = false; - bool _served = false; @visibleForTesting bool launchedInBrowser = false; @@ -105,7 +104,6 @@ class FlutterResidentDevtoolsHandler implements ResidentDevtoolsHandler { _devToolsLauncher.devToolsUrl = devToolsServerAddress; } else { await _devToolsLauncher.serve(); - _served = true; } await _devToolsLauncher.ready; // Do not attempt to print debugger list if the connection has failed or if we're shutting down. @@ -305,7 +303,7 @@ class FlutterResidentDevtoolsHandler implements ResidentDevtoolsHandler { @override Future shutdown() async { _shutdown = true; - if (_devToolsLauncher == null || !_served) { + if (_devToolsLauncher == null) { return; } _readyToAnnounce = false; diff --git a/packages/flutter_tools/lib/src/resident_runner.dart b/packages/flutter_tools/lib/src/resident_runner.dart index b88ba4b1664..38dea5eceea 100644 --- a/packages/flutter_tools/lib/src/resident_runner.dart +++ b/packages/flutter_tools/lib/src/resident_runner.dart @@ -8,7 +8,6 @@ import 'package:meta/meta.dart'; import 'package:package_config/package_config.dart'; import 'package:vm_service/vm_service.dart' as vm_service; -import 'android/android_device.dart'; import 'application_package.dart'; import 'artifacts.dart'; import 'asset.dart'; @@ -346,7 +345,8 @@ class FlutterDevice { globals.printTrace('Successfully connected to service protocol: $vmServiceUri'); vmService = service; - (await device!.getLogReader(app: package)).connectedVMService = vmService; + await (await device!.getLogReader(app: package)) + .provideVmService(vmService!); completer.complete(); await subscription.cancel(); }, onError: (dynamic error) { @@ -417,24 +417,6 @@ class FlutterDevice { _loggingSubscription = null; } - /// Attempts to set up reading logs from the Flutter app on the device. - /// - /// This can fail if the device if no longer connected. - Future tryInitLogReader() async { - final vm_service.VM? vm = await vmService!.getVmGuarded(); - final DeviceLogReader logReader = await device!.getLogReader(app: package); - if (vm == null && logReader is AdbLogReader) { - // TODO(andrewkolos): This is a temporary, hacky fix for - // https://github.com/flutter/flutter/issues/155795 that emphasizes - // simplicity for the sake of being suitable for cherry-picking. - globals.printError( - 'Unable to initiate adb log filtering for device' - '${device?.name}. Logs from the device may be more verbose than usual.', - ); - } - logReader.appPid = vm?.pid; - } - Future runHot({ required HotRunner hotRunner, String? route, @@ -1053,7 +1035,6 @@ abstract class ResidentRunner extends ResidentHandlers { this.flutterDevices, { required this.target, required this.debuggingOptions, - required bool useImplicitPubspecResolution, String? projectRootPath, this.stayResident = true, this.hotMode = true, @@ -1064,7 +1045,6 @@ abstract class ResidentRunner extends ResidentHandlers { packagesFilePath = debuggingOptions.buildInfo.packageConfigPath, projectRootPath = projectRootPath ?? globals.fs.currentDirectory.path, _dillOutputPath = dillOutputPath, - _useImplicitPubspecResolution = useImplicitPubspecResolution, artifactDirectory = dillOutputPath == null ? globals.fs.systemTempDirectory.createTempSync('flutter_tool.') : globals.fs.file(dillOutputPath).parent, @@ -1097,7 +1077,6 @@ abstract class ResidentRunner extends ResidentHandlers { @override final bool stayResident; final String? _dillOutputPath; - final bool _useImplicitPubspecResolution; /// The parent location of the incremental artifacts. final Directory artifactDirectory; final String packagesFilePath; @@ -1139,6 +1118,16 @@ abstract class ResidentRunner extends ResidentHandlers { return 'main.dart${swap ? '.swap' : ''}.dill'; } + /// Whether the app being instrumented by the runner should be stopped during + /// cleanup. + /// + /// A detached app can happen one of two ways: + /// - [run] is used, and then the created application is manually [detach]ed; + /// - [attach] is used to explicitly connect to an already running app. + @protected + @visibleForTesting + bool stopAppDuringCleanup = true; + bool get debuggingEnabled => debuggingOptions.debuggingEnabled; @override @@ -1224,7 +1213,6 @@ abstract class ResidentRunner extends ResidentHandlers { // Needed for Dart plugin registry generation. kTargetFile: mainPath, }, - useImplicitPubspecResolution: _useImplicitPubspecResolution, ); final CompositeTarget compositeTarget = CompositeTarget([ @@ -1276,7 +1264,10 @@ abstract class ResidentRunner extends ResidentHandlers { } @override + @mustCallSuper Future detach() async { + stopAppDuringCleanup = false; + // TODO(bkonyi): remove when ready to serve DevTools from DDS. await residentDevtoolsHandler!.shutdown(); await stopEchoingDeviceLog(); @@ -1420,6 +1411,7 @@ abstract class ResidentRunner extends ResidentHandlers { } } + @protected void appFinished() { if (_finished.isCompleted) { return; diff --git a/packages/flutter_tools/lib/src/run_cold.dart b/packages/flutter_tools/lib/src/run_cold.dart index b07ee54dbb1..cfe5979d1e1 100644 --- a/packages/flutter_tools/lib/src/run_cold.dart +++ b/packages/flutter_tools/lib/src/run_cold.dart @@ -18,7 +18,6 @@ class ColdRunner extends ResidentRunner { super.flutterDevices, { required super.target, required super.debuggingOptions, - required super.useImplicitPubspecResolution, this.traceStartup = false, this.awaitFirstFrameWhenTracing = true, this.applicationBinary, @@ -105,7 +104,6 @@ class ColdRunner extends ResidentRunner { if (device!.vmService == null) { continue; } - await device.tryInitLogReader(); globals.printTrace('Connected to ${device.device!.name}'); } @@ -154,9 +152,6 @@ class ColdRunner extends ResidentRunner { return 2; } - for (final FlutterDevice? device in flutterDevices) { - await device!.tryInitLogReader(); - } for (final FlutterDevice? device in flutterDevices) { final List views = await device!.vmService!.getFlutterViews(); for (final FlutterView view in views) { diff --git a/packages/flutter_tools/lib/src/run_hot.dart b/packages/flutter_tools/lib/src/run_hot.dart index 79634f75ca3..0b7e525de00 100644 --- a/packages/flutter_tools/lib/src/run_hot.dart +++ b/packages/flutter_tools/lib/src/run_hot.dart @@ -79,7 +79,6 @@ class HotRunner extends ResidentRunner { super.flutterDevices, { required super.target, required super.debuggingOptions, - required super.useImplicitPubspecResolution, this.benchmarkMode = false, this.applicationBinary, this.hostIsIde = false, @@ -91,13 +90,11 @@ class HotRunner extends ResidentRunner { StopwatchFactory stopwatchFactory = const StopwatchFactory(), ReloadSourcesHelper reloadSourcesHelper = defaultReloadSourcesHelper, ReassembleHelper reassembleHelper = _defaultReassembleHelper, - HotRunnerNativeAssetsBuilder? nativeAssetsBuilder, String? nativeAssetsYamlFile, required Analytics analytics, }) : _stopwatchFactory = stopwatchFactory, _reloadSourcesHelper = reloadSourcesHelper, _reassembleHelper = reassembleHelper, - _nativeAssetsBuilder = nativeAssetsBuilder, _nativeAssetsYamlFile = nativeAssetsYamlFile, _analytics = analytics, super( @@ -126,16 +123,12 @@ class HotRunner extends ResidentRunner { /// reload process do not have this issue. bool _swap = false; - /// Whether the resident runner has correctly attached to the running application. - bool _didAttach = false; - final Map> benchmarkData = >{}; String? _targetPlatform; String? _sdkName; bool? _emulator; - final HotRunnerNativeAssetsBuilder? _nativeAssetsBuilder; final String? _nativeAssetsYamlFile; String? flavor; @@ -176,7 +169,7 @@ class HotRunner extends ResidentRunner { if (!result.isOk) { throw vm_service.RPCError( 'Unable to reload sources', - RPCErrorCodes.kInternalError, + vm_service.RPCErrorKind.kInternalError.code, '', ); } @@ -188,7 +181,7 @@ class HotRunner extends ResidentRunner { if (!result.isOk) { throw vm_service.RPCError( 'Unable to restart', - RPCErrorCodes.kInternalError, + vm_service.RPCErrorKind.kInternalError.code, '', ); } @@ -213,23 +206,41 @@ class HotRunner extends ResidentRunner { await device.generator!.compileExpression(expression, definitions, definitionTypes, typeDefinitions, typeBounds, typeDefaults, libraryUri, klass, method, isStatic); - if (compilerOutput != null && compilerOutput.expressionData != null) { - return base64.encode(compilerOutput.expressionData!); + if (compilerOutput != null) { + if (compilerOutput.errorCount == 0 && compilerOutput.expressionData != null) { + return base64.encode(compilerOutput.expressionData!); + } else if (compilerOutput.errorCount > 0 && compilerOutput.errorMessage != null) { + throw VmServiceExpressionCompilationException(compilerOutput.errorMessage!); + } } } } throw Exception('Failed to compile $expression'); } - // Returns the exit code of the flutter tool process, like [run]. @override + @nonVirtual Future attach({ Completer? connectionInfoCompleter, Completer? appStartedCompleter, bool allowExistingDdsInstance = false, bool needsFullRestart = true, }) async { - _didAttach = true; + stopAppDuringCleanup = false; + return _attach( + connectionInfoCompleter: connectionInfoCompleter, + appStartedCompleter: appStartedCompleter, + allowExistingDdsInstance: allowExistingDdsInstance, + needsFullRestart: needsFullRestart, + ); + } + + Future _attach({ + Completer? connectionInfoCompleter, + Completer? appStartedCompleter, + bool allowExistingDdsInstance = false, + bool needsFullRestart = true, + }) async { try { await connectToServiceProtocol( reloadSources: _reloadSourcesService, @@ -262,8 +273,7 @@ class HotRunner extends ResidentRunner { } for (final FlutterDevice? device in flutterDevices) { - await device!.tryInitLogReader(); - device + device! .developmentShaderCompiler .configureCompiler(device.targetPlatform); } @@ -365,20 +375,9 @@ class HotRunner extends ResidentRunner { }) async { await _calculateTargetPlatform(); - final Uri? nativeAssetsYaml; - if (_nativeAssetsYamlFile != null) { - nativeAssetsYaml = globals.fs.path.toUri(_nativeAssetsYamlFile); - } else { - final Uri projectUri = Uri.directory(projectRootPath); - nativeAssetsYaml = await _nativeAssetsBuilder?.dryRun( - projectUri: projectUri, - fileSystem: fileSystem, - flutterDevices: flutterDevices, - logger: logger, - packageConfigPath: debuggingOptions.buildInfo.packageConfigPath, - packageConfig: debuggingOptions.buildInfo.packageConfig, - ); - } + final Uri? nativeAssetsYaml = _nativeAssetsYamlFile != null + ? globals.fs.path.toUri(_nativeAssetsYamlFile) + : null; final Stopwatch appStartedTimer = Stopwatch()..start(); final File mainFile = globals.fs.file(mainPath); @@ -466,7 +465,7 @@ class HotRunner extends ResidentRunner { return 1; } - return attach( + return _attach( connectionInfoCompleter: connectionInfoCompleter, appStartedCompleter: appStartedCompleter, needsFullRestart: false, @@ -1144,7 +1143,7 @@ class HotRunner extends ResidentRunner { } else { commandHelp.hWithoutDetails.print(); } - if (_didAttach) { + if (stopAppDuringCleanup) { commandHelp.d.print(); } commandHelp.c.print(); @@ -1239,13 +1238,14 @@ class HotRunner extends ResidentRunner { @override Future cleanupAfterSignal() async { + await residentDevtoolsHandler!.shutdown(); await stopEchoingDeviceLog(); await hotRunnerConfig!.runPreShutdownOperations(); - if (_didAttach) { - appFinished(); - } else { - await exitApp(); + shutdownDartDevelopmentService(); + if (stopAppDuringCleanup) { + return exitApp(); } + appFinished(); } @override @@ -1694,16 +1694,3 @@ class ReasonForCancelling { return '$message.\nTry performing a hot restart instead.'; } } - -/// An interface to enable overriding native assets build logic in other -/// build systems. -abstract class HotRunnerNativeAssetsBuilder { - Future dryRun({ - required Uri projectUri, - required FileSystem fileSystem, - required List flutterDevices, - required String packageConfigPath, - required PackageConfig packageConfig, - required Logger logger, - }); -} diff --git a/packages/flutter_tools/lib/src/runner/flutter_command.dart b/packages/flutter_tools/lib/src/runner/flutter_command.dart index 44b573a112e..4e29de50593 100644 --- a/packages/flutter_tools/lib/src/runner/flutter_command.dart +++ b/packages/flutter_tools/lib/src/runner/flutter_command.dart @@ -31,7 +31,6 @@ import '../preview_device.dart'; import '../project.dart'; import '../reporting/reporting.dart'; import '../reporting/unified_analytics.dart'; -import '../web/compile.dart'; import 'flutter_command_runner.dart'; import 'target_devices.dart'; @@ -154,7 +153,6 @@ abstract final class FlutterOptions { static const String kFatalWarnings = 'fatal-warnings'; static const String kUseApplicationBinary = 'use-application-binary'; static const String kWebBrowserFlag = 'web-browser-flag'; - static const String kWebRendererFlag = 'web-renderer'; static const String kWebResourcesCdnFlag = 'web-resources-cdn'; static const String kWebWasmFlag = 'wasm'; } @@ -251,7 +249,7 @@ abstract class FlutterCommand extends Command { argParser.addOption('web-hostname', defaultsTo: 'localhost', help: - 'The hostname that the web sever will use to resolve an IP to serve ' + 'The hostname that the web server will use to resolve an IP to serve ' 'from. The unresolved hostname is used to launch Chrome when using ' 'the chrome Device. The name "any" may also be used to serve on any ' 'IPV4 for either the Chrome or web-server device.', @@ -707,32 +705,6 @@ abstract class FlutterCommand extends Command { ); } - // This option is deprecated and is no longer publicly supported, and - // therefore is hidden. - // - // The option still exists for internal testing, and to give existing users - // time to migrate off the HTML renderer, but it is no longer advertised as a - // supported mode. - // - // See also: - // * https://github.com/flutter/flutter/issues/151786 - // * https://github.com/flutter/flutter/issues/145954 - void usesWebRendererOption() { - argParser.addOption( - hide: true, - FlutterOptions.kWebRendererFlag, - allowed: WebRendererMode.values.map((WebRendererMode e) => e.name), - help: 'This option is deprecated and will be removed in a future Flutter ' - 'release.\n' - 'Selects the renderer implementation to use when building for the ' - 'web. The supported renderers are "canvaskit" when compiling to ' - 'JavaScript, and "skwasm" when compiling to WebAssembly. Other ' - 'renderer and compiler combinations are no longer supported. ' - 'Consider migrating your app to a supported renderer.', - allowedHelp: CliEnum.allowedHelp(WebRendererMode.values) - ); - } - void usesWebResourcesCdnFlag() { argParser.addFlag( FlutterOptions.kWebResourcesCdnFlag, @@ -1770,7 +1742,6 @@ Run 'flutter -h' (or 'flutter -h') for available flutter commands and projectDir: project.directory, packageConfigPath: packageConfigPath(), generateDartPluginRegistry: true, - useImplicitPubspecResolution: globalResults!.flag(FlutterGlobalOptions.kImplicitPubspecResolution), ); await pub.get( @@ -1793,7 +1764,6 @@ Run 'flutter -h' (or 'flutter -h') for available flutter commands and } await project.regeneratePlatformSpecificTooling( allowedPlugins: allowedPlugins, - useImplicitPubspecResolution: boolArg(FlutterGlobalOptions.kImplicitPubspecResolution, global: true), ); if (reportNullSafety) { await _sendNullSafetyAnalyticsEvents(project); diff --git a/packages/flutter_tools/lib/src/test/flutter_platform.dart b/packages/flutter_tools/lib/src/test/flutter_platform.dart index 1e3e2b4a034..8ba1919d490 100644 --- a/packages/flutter_tools/lib/src/test/flutter_platform.dart +++ b/packages/flutter_tools/lib/src/test/flutter_platform.dart @@ -15,6 +15,7 @@ import '../base/async_guard.dart'; import '../base/common.dart'; import '../base/file_system.dart'; import '../base/io.dart'; +import '../base/process.dart'; import '../build_info.dart'; import '../cache.dart'; import '../compile.dart'; @@ -26,6 +27,7 @@ import '../native_assets.dart'; import '../project.dart'; import '../test/test_wrapper.dart'; +import '../vmservice.dart'; import 'flutter_tester_device.dart'; import 'font_config_manager.dart'; import 'integration_test_device.dart'; @@ -307,6 +309,7 @@ class FlutterPlatform extends PlatformPlugin { this.testTimeRecorder, this.nativeAssetsBuilder, this.buildInfo, + this.shutdownHooks, }); final String shellPath; @@ -325,6 +328,7 @@ class FlutterPlatform extends PlatformPlugin { final TestTimeRecorder? testTimeRecorder; final TestCompilerNativeAssetsBuilder? nativeAssetsBuilder; final BuildInfo? buildInfo; + final ShutdownHooks? shutdownHooks; /// The device to run the test on for Integration Tests. /// @@ -422,8 +426,12 @@ class FlutterPlatform extends PlatformPlugin { await compiler!.compiler!.compileExpression(expression, definitions, definitionTypes, typeDefinitions, typeBounds, typeDefaults, libraryUri, klass, method, isStatic); - if (compilerOutput != null && compilerOutput.expressionData != null) { - return base64.encode(compilerOutput.expressionData!); + if (compilerOutput != null) { + if (compilerOutput.errorCount == 0 && compilerOutput.expressionData != null) { + return base64.encode(compilerOutput.expressionData!); + } else if (compilerOutput.errorCount > 0 && compilerOutput.errorMessage != null) { + throw VmServiceExpressionCompilationException(compilerOutput.errorMessage!); + } } throw Exception('Failed to compile $expression'); } @@ -476,8 +484,35 @@ class FlutterPlatform extends PlatformPlugin { _AsyncError? outOfBandError; // error that we couldn't send to the harness that we need to send via our future - final List finalizers = []; // Will be run in reverse order. + // Will be run in reverse order. + final List finalizers = []; + bool ranFinalizers = false; bool controllerSinkClosed = false; + Future finalize() async { + if (ranFinalizers) { + return; + } + ranFinalizers = true; + globals.printTrace('test $ourTestCount: cleaning up...'); + for (final Finalizer finalizer in finalizers.reversed) { + try { + await finalizer(); + } on Exception catch (error, stack) { + globals.printTrace('test $ourTestCount: error while cleaning up; ${controllerSinkClosed ? "reporting to console" : "sending to test framework"}'); + if (!controllerSinkClosed) { + testHarnessChannel.sink.addError(error, stack); + } else { + globals.printError('unhandled error during finalization of test:\n$testPath\n$error\n$stack'); + outOfBandError ??= _AsyncError(error, stack); + } + } + } + } + + // If the flutter CLI is forcibly terminated, cleanup processes. + final ShutdownHooks shutdownHooks = this.shutdownHooks ?? globals.shutdownHooks; + shutdownHooks.addShutdownHook(finalize); + try { // Callback can't throw since it's just setting a variable. unawaited(testHarnessChannel.sink.done.whenComplete(() { @@ -494,7 +529,6 @@ class FlutterPlatform extends PlatformPlugin { flutterProject, precompiledDillPath: precompiledDillPath, testTimeRecorder: testTimeRecorder, - nativeAssetsBuilder: nativeAssetsBuilder, ); final Uri uri = globals.fs.file(path).uri; // Trigger a compilation to initialize the resident compiler. @@ -521,7 +555,6 @@ class FlutterPlatform extends PlatformPlugin { debuggingOptions.buildInfo, flutterProject, testTimeRecorder: testTimeRecorder, - nativeAssetsBuilder: nativeAssetsBuilder, ); mainDart = await compiler!.compile(globals.fs.file(mainDart).uri); @@ -608,21 +641,7 @@ class FlutterPlatform extends PlatformPlugin { outOfBandError ??= _AsyncError(reportedError, reportedStackTrace); } } finally { - globals.printTrace('test $ourTestCount: cleaning up...'); - // Finalizers are treated like a stack; run them in reverse order. - for (final Finalizer finalizer in finalizers.reversed) { - try { - await finalizer(); - } on Exception catch (error, stack) { - globals.printTrace('test $ourTestCount: error while cleaning up; ${controllerSinkClosed ? "reporting to console" : "sending to test framework"}'); - if (!controllerSinkClosed) { - testHarnessChannel.sink.addError(error, stack); - } else { - globals.printError('unhandled error during finalization of test:\n$testPath\n$error\n$stack'); - outOfBandError ??= _AsyncError(error, stack); - } - } - } + await finalize(); if (!controllerSinkClosed) { // Waiting below with await. unawaited(testHarnessChannel.sink.close()); diff --git a/packages/flutter_tools/lib/src/test/flutter_tester_device.dart b/packages/flutter_tools/lib/src/test/flutter_tester_device.dart index 0e9b9b3175d..cb78d35a1d0 100644 --- a/packages/flutter_tools/lib/src/test/flutter_tester_device.dart +++ b/packages/flutter_tools/lib/src/test/flutter_tester_device.dart @@ -176,7 +176,6 @@ class FlutterTesterTestDevice extends TestDevice { if (debuggingOptions.enableDds) { logger.printTrace('test $id: Starting Dart Development Service'); - await _ddsLauncher.startDartDevelopmentServiceFromDebuggingOptions( detectedUri, debuggingOptions: debuggingOptions, diff --git a/packages/flutter_tools/lib/src/test/integration_test_device.dart b/packages/flutter_tools/lib/src/test/integration_test_device.dart index 598bcc7423c..0d9bd39b42a 100644 --- a/packages/flutter_tools/lib/src/test/integration_test_device.dart +++ b/packages/flutter_tools/lib/src/test/integration_test_device.dart @@ -8,6 +8,7 @@ import 'package:stream_channel/stream_channel.dart'; import 'package:vm_service/vm_service.dart' as vm_service; import '../application_package.dart'; +import '../base/dds.dart'; import '../build_info.dart'; import '../device.dart'; import '../globals.dart' as globals; @@ -32,6 +33,7 @@ class IntegrationTestTestDevice implements TestDevice { final DebuggingOptions debuggingOptions; final String? userIdentifier; final CompileExpression? compileExpression; + late final DartDevelopmentService _ddsLauncher = DartDevelopmentService(logger: globals.logger); ApplicationPackage? _applicationPackage; final Completer _finished = Completer(); @@ -62,7 +64,7 @@ class IntegrationTestTestDevice implements TestDevice { if (!launchResult.started) { throw TestDeviceException('Unable to start the app on the device.', StackTrace.current); } - final Uri? vmServiceUri = launchResult.vmServiceUri; + Uri? vmServiceUri = launchResult.vmServiceUri; if (vmServiceUri == null) { throw TestDeviceException('The VM Service is not available on the test device.', StackTrace.current); } @@ -70,11 +72,21 @@ class IntegrationTestTestDevice implements TestDevice { // No need to set up the log reader because the logs are captured and // streamed to the package:test_core runner. + if (debuggingOptions.enableDds) { + globals.printTrace('test $id: Starting Dart Development Service'); + await _ddsLauncher.startDartDevelopmentServiceFromDebuggingOptions( + vmServiceUri, + debuggingOptions: debuggingOptions, + ); + globals.printTrace('test $id: Dart Development Service started at ${_ddsLauncher.uri}, forwarding to VM service at $vmServiceUri.'); + vmServiceUri = _ddsLauncher.uri; + } + _gotProcessVmServiceUri.complete(vmServiceUri); globals.printTrace('test $id: Connecting to vm service'); final FlutterVmService vmService = await connectToVmService( - vmServiceUri, + vmServiceUri!, logger: globals.logger, compileExpression: compileExpression, ).timeout( @@ -131,6 +143,7 @@ class IntegrationTestTestDevice implements TestDevice { } await device.dispose(); + _ddsLauncher.shutdown(); _finished.complete(); } diff --git a/packages/flutter_tools/lib/src/test/runner.dart b/packages/flutter_tools/lib/src/test/runner.dart index 54613922fe3..ec795cc9edd 100644 --- a/packages/flutter_tools/lib/src/test/runner.dart +++ b/packages/flutter_tools/lib/src/test/runner.dart @@ -766,9 +766,6 @@ class SpawnPlugin extends PlatformPlugin { rootTestIsolateSpawnerSourceFile: rootTestIsolateSpawnerSourceFile, ); - final Uri? nativeAssetsYaml = await nativeAssetsBuilder?.build( - debuggingOptions.buildInfo, - ); await _compileFile( debuggingOptions: debuggingOptions, @@ -777,7 +774,6 @@ class SpawnPlugin extends PlatformPlugin { sourceFile: childTestIsolateSpawnerSourceFile, outputDillFile: childTestIsolateSpawnerDillFile, testTimeRecorder: testTimeRecorder, - nativeAssetsYaml: nativeAssetsYaml, ); await _compileFile( diff --git a/packages/flutter_tools/lib/src/test/test_compiler.dart b/packages/flutter_tools/lib/src/test/test_compiler.dart index 9c09ba92c40..fb98680a0ab 100644 --- a/packages/flutter_tools/lib/src/test/test_compiler.dart +++ b/packages/flutter_tools/lib/src/test/test_compiler.dart @@ -15,7 +15,6 @@ import '../bundle.dart'; import '../compile.dart'; import '../flutter_plugins.dart'; import '../globals.dart' as globals; -import '../native_assets.dart'; import '../project.dart'; import 'test_time_recorder.dart'; @@ -49,7 +48,6 @@ class TestCompiler { this.flutterProject, { String? precompiledDillPath, this.testTimeRecorder, - TestCompilerNativeAssetsBuilder? nativeAssetsBuilder, }) : testFilePath = precompiledDillPath ?? globals.fs.path.join( flutterProject!.directory.path, getBuildDirectory(), @@ -59,8 +57,7 @@ class TestCompiler { dartDefines: buildInfo.dartDefines, extraFrontEndOptions: buildInfo.extraFrontEndOptions, )), - shouldCopyDillFile = precompiledDillPath == null, - _nativeAssetsBuilder = nativeAssetsBuilder { + shouldCopyDillFile = precompiledDillPath == null { // Compiler maintains and updates single incremental dill file. // Incremental compilation requests done for each test copy that file away // for independent execution. @@ -81,8 +78,6 @@ class TestCompiler { final String testFilePath; final bool shouldCopyDillFile; final TestTimeRecorder? testTimeRecorder; - final TestCompilerNativeAssetsBuilder? _nativeAssetsBuilder; - ResidentCompiler? compiler; late File outputDill; @@ -169,8 +164,6 @@ class TestCompiler { invalidatedRegistrantFiles.add(flutterProject!.dartPluginRegistrant.absolute.uri); } - final Uri? nativeAssetsYaml = await _nativeAssetsBuilder?.build(buildInfo); - final CompilerOutput? compilerOutput = await compiler!.recompile( request.mainUri, [request.mainUri, ...invalidatedRegistrantFiles], @@ -179,7 +172,6 @@ class TestCompiler { projectRootPath: flutterProject?.directory.absolute.path, checkDartPluginRegistry: true, fs: globals.fs, - nativeAssetsYaml: nativeAssetsYaml, ); final String? outputPath = compilerOutput?.outputFilename; diff --git a/packages/flutter_tools/lib/src/tester/flutter_tester.dart b/packages/flutter_tools/lib/src/tester/flutter_tester.dart index 1ee57e3251c..651ab118854 100644 --- a/packages/flutter_tools/lib/src/tester/flutter_tester.dart +++ b/packages/flutter_tools/lib/src/tester/flutter_tester.dart @@ -51,7 +51,6 @@ class FlutterTesterDevice extends Device { required super.logger, required FileSystem fileSystem, required Artifacts artifacts, - required bool useImplicitPubspecResolution, TestCompilerNativeAssetsBuilder? nativeAssetsBuilder, }) : _processManager = processManager, _flutterVersion = flutterVersion, @@ -59,7 +58,6 @@ class FlutterTesterDevice extends Device { _fileSystem = fileSystem, _artifacts = artifacts, _nativeAssetsBuilder = nativeAssetsBuilder, - _useImplicitPubspecResolution = useImplicitPubspecResolution, super( platformType: null, category: null, @@ -72,7 +70,6 @@ class FlutterTesterDevice extends Device { final FileSystem _fileSystem; final Artifacts _artifacts; final TestCompilerNativeAssetsBuilder? _nativeAssetsBuilder; - final bool _useImplicitPubspecResolution; Process? _process; final DevicePortForwarder _portForwarder = const NoOpDevicePortForwarder(); @@ -167,7 +164,6 @@ class FlutterTesterDevice extends Device { applicationKernelFilePath: applicationKernelFilePath, platform: TargetPlatform.tester, assetDirPath: assetDirectory.path, - useImplicitPubspecResolution: _useImplicitPubspecResolution, ); final List command = [ @@ -269,7 +265,6 @@ class FlutterTesterDevices extends PollingDeviceDiscovery { required ProcessManager processManager, required Logger logger, required FlutterVersion flutterVersion, - required bool useImplicitPubspecResolution, TestCompilerNativeAssetsBuilder? nativeAssetsBuilder, }) : _testerDevice = FlutterTesterDevice( kTesterDeviceId, @@ -279,7 +274,6 @@ class FlutterTesterDevices extends PollingDeviceDiscovery { logger: logger, flutterVersion: flutterVersion, nativeAssetsBuilder: nativeAssetsBuilder, - useImplicitPubspecResolution: useImplicitPubspecResolution, ), super('Flutter tester'); diff --git a/packages/flutter_tools/lib/src/update_packages_pins.dart b/packages/flutter_tools/lib/src/update_packages_pins.dart index 0fe6da29bdf..99543dfefb9 100644 --- a/packages/flutter_tools/lib/src/update_packages_pins.dart +++ b/packages/flutter_tools/lib/src/update_packages_pins.dart @@ -23,6 +23,7 @@ const Map kManuallyPinnedDependencies = { 'flutter_gallery_assets': '1.0.2', // Tests depend on the exact version. 'flutter_template_images': '4.2.0', // Must always exactly match flutter_tools template. 'google_mobile_ads': '5.1.0', // https://github.com/flutter/flutter/issues/156912 + 'intl': '0.19.0', // 0.20.0 introduces new transitive dependencies that are not (yet) cleared in Flutter's allow list. 'native_assets_builder': '0.9.0', // Under active development with breaking changes until 1.0.0. Manually rolled by @dcharkes. 'native_assets_cli': '0.9.0', // Under active development with breaking changes until 1.0.0. Manually rolled by @dcharkes. 'material_color_utilities': '0.11.1', // Keep pinned to latest until 1.0.0. diff --git a/packages/flutter_tools/lib/src/vmservice.dart b/packages/flutter_tools/lib/src/vmservice.dart index 98ae0bcdf80..89b16df6cbd 100644 --- a/packages/flutter_tools/lib/src/vmservice.dart +++ b/packages/flutter_tools/lib/src/vmservice.dart @@ -21,6 +21,7 @@ import 'version.dart'; const String kResultType = 'type'; const String kResultTypeSuccess = 'Success'; +const String kError = 'error'; const String kGetSkSLsMethod = '_flutter.getSkSLs'; const String kSetAssetBundlePathMethod = '_flutter.setAssetBundlePath'; @@ -58,29 +59,6 @@ set openChannelForTesting(WebSocketConnector? connector) { _openChannel = connector ?? _defaultOpenChannel; } -/// The error codes for the JSON-RPC standard, including VM service specific -/// error codes. -/// -/// See also: https://www.jsonrpc.org/specification#error_object -abstract class RPCErrorCodes { - /// The method does not exist or is not available. - static const int kMethodNotFound = -32601; - - /// Invalid method parameter(s), such as a mismatched type. - static const int kInvalidParams = -32602; - - /// Internal JSON-RPC error. - static const int kInternalError = -32603; - - /// Application specific error codes. - static const int kServerError = -32000; - - /// Non-standard JSON-RPC error codes: - - /// The VM service or extension service has disappeared. - static const int kServiceDisappeared = 112; -} - /// A function that reacts to the invocation of the 'reloadSources' service. /// /// The VM Service Protocol allows clients to register custom services that @@ -268,13 +246,29 @@ Future setUpVmService({ final String? method = params['method'] as String?; final bool isStatic = _validateRpcBoolParam('compileExpression', params, 'isStatic'); - final String kernelBytesBase64 = await compileExpression(isolateId, - expression, definitions, definitionTypes, typeDefinitions, typeBounds, typeDefaults, - libraryUri, klass, method, isStatic); - return { - kResultType: kResultTypeSuccess, - 'result': {'kernelBytes': kernelBytesBase64}, - }; + try { + final String kernelBytesBase64 = await compileExpression(isolateId, + expression, definitions, definitionTypes, typeDefinitions, typeBounds, typeDefaults, + libraryUri, klass, method, isStatic); + return { + kResultType: kResultTypeSuccess, + 'result': {'kernelBytes': kernelBytesBase64}, + }; + } on VmServiceExpressionCompilationException catch (e) { + // In most situations, we'd just let VmService catch this exception and + // build the error response. However, in this case we build the error + // response manually and return it to avoid including the stack trace + // from the tool in the response, instead returning the compilation + // error message in the 'details' property of the returned error object. + return { + kError: vm_service.RPCError.withDetails( + 'compileExpression', + vm_service.RPCErrorKind.kExpressionCompilationError.code, + vm_service.RPCErrorKind.kExpressionCompilationError.message, + details: e.errorMessage, + ).toMap(), + }; + } }); registrationRequests.add(vmService.registerService(kCompileExpressionServiceName, kFlutterToolAlias)); } @@ -424,7 +418,7 @@ String _validateRpcStringParam(String methodName, Map params, S if (value is! String || value.isEmpty) { throw vm_service.RPCError( methodName, - RPCErrorCodes.kInvalidParams, + vm_service.RPCErrorKind.kInvalidParams.code, "Invalid '$paramName': $value", ); } @@ -436,7 +430,7 @@ bool _validateRpcBoolParam(String methodName, Map params, Strin if (value != null && value is! bool) { throw vm_service.RPCError( methodName, - RPCErrorCodes.kInvalidParams, + vm_service.RPCErrorKind.kInvalidParams.code, "Invalid '$paramName': $value", ); } @@ -498,7 +492,7 @@ class FlutterVmService { try { return await service.getVM(); } on vm_service.RPCError catch (err) { - if (err.code == RPCErrorCodes.kServiceDisappeared || + if (err.code == vm_service.RPCErrorKind.kServiceDisappeared.code || err.message.contains('Service connection disposed')) { globals.printTrace('VmService.getVm call failed: $err'); return null; @@ -519,7 +513,7 @@ class FlutterVmService { // and should begin to shutdown due to the service connection closing. // Swallow the exception here and let the shutdown logic elsewhere deal // with cleaning up. - if (e.code == RPCErrorCodes.kServiceDisappeared || + if (e.code == vm_service.RPCErrorKind.kServiceDisappeared.code || e.message.contains('Service connection disposed')) { return null; } @@ -589,8 +583,7 @@ class FlutterVmService { await service.streamListen(vm_service.EventStreams.kIsolate); } on vm_service.RPCError catch (e) { // Do nothing if the tool is already subscribed. - const int streamAlreadySubscribed = 103; - if (e.code != streamAlreadySubscribed) { + if (e.code != vm_service.RPCErrorKind.kStreamAlreadySubscribed.code) { rethrow; } } @@ -890,8 +883,8 @@ class FlutterVmService { } on vm_service.RPCError catch (err) { // If an application is not using the framework or the VM service // disappears while handling a request, return null. - if ((err.code == RPCErrorCodes.kMethodNotFound) || - (err.code == RPCErrorCodes.kServiceDisappeared) || + if ((err.code == vm_service.RPCErrorKind.kMethodNotFound.code) || + (err.code == vm_service.RPCErrorKind.kServiceDisappeared.code) || (err.message.contains('Service connection disposed'))) { return null; } @@ -1029,7 +1022,7 @@ class FlutterVmService { onError: (Object? error, StackTrace stackTrace) { if (error is vm_service.SentinelException || error == null || - (error is vm_service.RPCError && error.code == RPCErrorCodes.kServiceDisappeared)) { + (error is vm_service.RPCError && error.code == vm_service.RPCErrorKind.kServiceDisappeared.code)) { return null; } return Future.error(error, stackTrace); @@ -1045,7 +1038,7 @@ class FlutterVmService { onError: (Object? error, StackTrace stackTrace) { if (error is vm_service.SentinelException || error == null || - (error is vm_service.RPCError && error.code == RPCErrorCodes.kServiceDisappeared)) { + (error is vm_service.RPCError && error.code == vm_service.RPCErrorKind.kServiceDisappeared.code)) { return null; } return Future.error(error, stackTrace); @@ -1096,6 +1089,14 @@ class FlutterVmService { /// Thrown when the VM Service disappears while calls are being made to it. class VmServiceDisappearedException implements Exception { } +/// Thrown when the frontend service fails to compile an expression due to an +/// error. +class VmServiceExpressionCompilationException implements Exception { + const VmServiceExpressionCompilationException(this.errorMessage); + + final String errorMessage; +} + /// Whether the event attached to an [Isolate.pauseEvent] should be considered /// a "pause" event. bool isPauseEvent(String kind) { diff --git a/packages/flutter_tools/lib/src/web/compile.dart b/packages/flutter_tools/lib/src/web/compile.dart index 5928479a642..f8577f2d094 100644 --- a/packages/flutter_tools/lib/src/web/compile.dart +++ b/packages/flutter_tools/lib/src/web/compile.dart @@ -11,7 +11,6 @@ import '../base/file_system.dart'; import '../base/logger.dart'; import '../base/project_migrator.dart'; import '../base/terminal.dart'; -import '../base/utils.dart'; import '../build_info.dart'; import '../build_system/build_system.dart'; import '../cache.dart'; @@ -46,15 +45,13 @@ class WebBuilder { required Analytics analytics, required FlutterVersion flutterVersion, required FileSystem fileSystem, - required bool useImplicitPubspecResolution, }) : _logger = logger, _processManager = processManager, _buildSystem = buildSystem, _flutterUsage = usage, _analytics = analytics, _flutterVersion = flutterVersion, - _fileSystem = fileSystem, - _useImplicitPubspecResolution = useImplicitPubspecResolution; + _fileSystem = fileSystem; final Logger _logger; final ProcessManager _processManager; @@ -63,7 +60,6 @@ class WebBuilder { final Analytics _analytics; final FlutterVersion _flutterVersion; final FileSystem _fileSystem; - final bool _useImplicitPubspecResolution; Future buildWeb( FlutterProject flutterProject, @@ -74,8 +70,8 @@ class WebBuilder { String? baseHref, String? outputDirectoryPath, }) async { - final bool hasWebPlugins = - (await findPlugins(flutterProject, useImplicitPubspecResolution: true)).any((Plugin p) => p.platforms.containsKey(WebPlugin.kConfigKey)); + final bool hasWebPlugins = (await findPlugins(flutterProject)) + .any((Plugin p) => p.platforms.containsKey(WebPlugin.kConfigKey)); final Directory outputDirectory = outputDirectoryPath == null ? _fileSystem.directory(getWebBuildDirectory()) : _fileSystem.directory(outputDirectoryPath); @@ -89,7 +85,8 @@ class WebBuilder { final ProjectMigration migration = ProjectMigration(migrators); await migration.run(); - final Status status = _logger.startProgress('Compiling $target for the Web...'); + final Status status = + _logger.startProgress('Compiling $target for the Web...'); final Stopwatch sw = Stopwatch()..start(); try { final BuildResult result = await _buildSystem.build( @@ -97,7 +94,9 @@ class WebBuilder { Environment( projectDir: _fileSystem.currentDirectory, outputDir: outputDirectory, - buildDir: flutterProject.directory.childDirectory('.dart_tool').childDirectory('flutter_build'), + buildDir: flutterProject.directory + .childDirectory('.dart_tool') + .childDirectory('flutter_build'), defines: { kTargetFile: target, kHasWebPlugins: hasWebPlugins.toString(), @@ -114,15 +113,17 @@ class WebBuilder { usage: _flutterUsage, analytics: _analytics, cacheDir: globals.cache.getRoot(), - engineVersion: globals.artifacts!.usesLocalArtifacts ? null : _flutterVersion.engineRevision, + engineVersion: globals.artifacts!.usesLocalArtifacts + ? null + : _flutterVersion.engineRevision, flutterRootDir: _fileSystem.directory(Cache.flutterRoot), // Web uses a different Dart plugin registry. // https://github.com/flutter/flutter/issues/80406 generateDartPluginRegistry: false, - useImplicitPubspecResolution: _useImplicitPubspecResolution, )); if (!result.success) { - for (final ExceptionMeasurement measurement in result.exceptions.values) { + for (final ExceptionMeasurement measurement + in result.exceptions.values) { _logger.printError( 'Target ${measurement.target} failed: ${measurement.exception}', stackTrace: measurement.fatal ? measurement.stackTrace : null, @@ -161,7 +162,8 @@ class WebBuilder { )); final Duration elapsedDuration = sw.elapsed; - final String variableName = compilerConfigs.length > 1 ? 'dual-compile' : 'dart2js'; + final String variableName = + compilerConfigs.length > 1 ? 'dual-compile' : 'dart2js'; _flutterUsage.sendTiming( 'build', variableName, @@ -176,7 +178,7 @@ class WebBuilder { } /// Web rendering backend mode. -enum WebRendererMode implements CliEnum { +enum WebRendererMode { /// Auto detects which rendering backend to use. auto, @@ -189,11 +191,22 @@ enum WebRendererMode implements CliEnum { /// Always use skwasm. skwasm; - factory WebRendererMode.fromCliOption(String? webRendererString, {required bool useWasm}) { - if (webRendererString == null) { - return getDefault(useWasm: useWasm); + factory WebRendererMode.fromDartDefines(Iterable defines, { + required bool useWasm, + }) { + if (defines.contains('FLUTTER_WEB_AUTO_DETECT=true')) { + return auto; + } else if (defines.contains('FLUTTER_WEB_USE_SKIA=false') + && defines.contains('FLUTTER_WEB_USE_SKWASM=true')) { + return skwasm; + } else if (defines.contains('FLUTTER_WEB_USE_SKIA=true') + && defines.contains('FLUTTER_WEB_USE_SKWASM=false')) { + return canvaskit; + } else if (defines.contains('FLUTTER_WEB_USE_SKIA=false') + && defines.contains('FLUTTER_WEB_USE_SKWASM=false')) { + return html; // The horror! } - return WebRendererMode.values.byName(webRendererString); + return getDefault(useWasm: useWasm); } static WebRendererMode getDefault({required bool useWasm}) { @@ -215,13 +228,9 @@ enum WebRendererMode implements CliEnum { /// Returns a consistent deprecation warning for the WebRendererMode. String get deprecationWarning => - 'The HTML Renderer is deprecated. Do not use "--web-renderer=$name".' - '\nSee: https://docs.flutter.dev/to/web-html-renderer-deprecation'; + 'The HTML Renderer is deprecated and will be removed. Please, stop using it.' + '\nSee: https://docs.flutter.dev/to/web-html-renderer-deprecation'; - @override - String get cliName => kebabCase(name); - - @override String get helpText => switch (this) { auto => 'Use the HTML renderer on mobile devices, and CanvasKit on desktop devices.', @@ -232,48 +241,64 @@ enum WebRendererMode implements CliEnum { skwasm => 'Always use the experimental skwasm renderer.' }; + /// Returns [dartDefines] in a way usable from the CLI. + /// + /// This is used to start integration tests. + Iterable get toCliDartDefines => dartDefines.map( + (String define) => '--dart-define=$define'); + Iterable get dartDefines => switch (this) { - auto => [ + auto => const { 'FLUTTER_WEB_AUTO_DETECT=true', - ], - canvaskit => [ + }, + canvaskit => const { 'FLUTTER_WEB_AUTO_DETECT=false', 'FLUTTER_WEB_USE_SKIA=true', - ], - html => [ + 'FLUTTER_WEB_USE_SKWASM=false', + }, + html => const { 'FLUTTER_WEB_AUTO_DETECT=false', 'FLUTTER_WEB_USE_SKIA=false', - ], - skwasm => [ + 'FLUTTER_WEB_USE_SKWASM=false', + }, + skwasm => const { 'FLUTTER_WEB_AUTO_DETECT=false', 'FLUTTER_WEB_USE_SKIA=false', 'FLUTTER_WEB_USE_SKWASM=true', - ], + }, }; + /// Sets the dart defines for the currently selected WebRendererMode List updateDartDefines(List inputDefines) { final Set dartDefinesSet = inputDefines.toSet(); - if (!inputDefines.any((String d) => d.startsWith('FLUTTER_WEB_AUTO_DETECT=')) - && inputDefines.any((String d) => d.startsWith('FLUTTER_WEB_USE_SKIA='))) { - dartDefinesSet.removeWhere((String d) => d.startsWith('FLUTTER_WEB_USE_SKIA=')); - } - dartDefinesSet.addAll(dartDefines); + + dartDefinesSet + ..removeWhere((String d) { + return d.startsWith('FLUTTER_WEB_AUTO_DETECT=') || + d.startsWith('FLUTTER_WEB_USE_SKIA=') || + d.startsWith('FLUTTER_WEB_USE_SKWASM='); + }) + ..addAll(dartDefines); + return dartDefinesSet.toList(); } } /// The correct precompiled artifact to use for each build and render mode for DDC with AMD modules. // TODO(markzipan): delete this when DDC's AMD module system is deprecated, https://github.com/flutter/flutter/issues/142060. -const Map> kAmdDartSdkJsArtifactMap = >{ - WebRendererMode.auto: { - NullSafetyMode.sound: HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSoundSdk, +const Map> + kAmdDartSdkJsArtifactMap = + >{ + WebRendererMode.auto: { + NullSafetyMode.sound: + HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSoundSdk, NullSafetyMode.unsound: HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSdk, }, - WebRendererMode.canvaskit: { + WebRendererMode.canvaskit: { NullSafetyMode.sound: HostArtifact.webPrecompiledAmdCanvaskitSoundSdk, NullSafetyMode.unsound: HostArtifact.webPrecompiledAmdCanvaskitSdk, }, - WebRendererMode.html: { + WebRendererMode.html: { NullSafetyMode.sound: HostArtifact.webPrecompiledAmdSoundSdk, NullSafetyMode.unsound: HostArtifact.webPrecompiledAmdSdk, }, @@ -281,48 +306,63 @@ const Map> kAmdDartSdkJsArtif /// The correct source map artifact to use for each build and render mode for DDC with AMD modules. // TODO(markzipan): delete this when DDC's AMD module system is deprecated, https://github.com/flutter/flutter/issues/142060. -const Map> kAmdDartSdkJsMapArtifactMap = >{ - WebRendererMode.auto: { - NullSafetyMode.sound: HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSoundSdkSourcemaps, - NullSafetyMode.unsound: HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSdkSourcemaps, +const Map> + kAmdDartSdkJsMapArtifactMap = + >{ + WebRendererMode.auto: { + NullSafetyMode.sound: + HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSoundSdkSourcemaps, + NullSafetyMode.unsound: + HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSdkSourcemaps, }, - WebRendererMode.canvaskit: { - NullSafetyMode.sound: HostArtifact.webPrecompiledAmdCanvaskitSoundSdkSourcemaps, - NullSafetyMode.unsound: HostArtifact.webPrecompiledAmdCanvaskitSdkSourcemaps, + WebRendererMode.canvaskit: { + NullSafetyMode.sound: + HostArtifact.webPrecompiledAmdCanvaskitSoundSdkSourcemaps, + NullSafetyMode.unsound: + HostArtifact.webPrecompiledAmdCanvaskitSdkSourcemaps, }, - WebRendererMode.html: { + WebRendererMode.html: { NullSafetyMode.sound: HostArtifact.webPrecompiledAmdSoundSdkSourcemaps, NullSafetyMode.unsound: HostArtifact.webPrecompiledAmdSdkSourcemaps, }, }; /// The correct precompiled artifact to use for each build and render mode for DDC with DDC modules. -const Map> kDdcDartSdkJsArtifactMap = >{ - WebRendererMode.auto: { - NullSafetyMode.sound: HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSoundSdk, +const Map> + kDdcDartSdkJsArtifactMap = + >{ + WebRendererMode.auto: { + NullSafetyMode.sound: + HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSoundSdk, NullSafetyMode.unsound: HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSdk, }, - WebRendererMode.canvaskit: { + WebRendererMode.canvaskit: { NullSafetyMode.sound: HostArtifact.webPrecompiledDdcCanvaskitSoundSdk, NullSafetyMode.unsound: HostArtifact.webPrecompiledDdcCanvaskitSdk, }, - WebRendererMode.html: { + WebRendererMode.html: { NullSafetyMode.sound: HostArtifact.webPrecompiledDdcSoundSdk, NullSafetyMode.unsound: HostArtifact.webPrecompiledDdcSdk, }, }; /// The correct source map artifact to use for each build and render mode for DDC with DDC modules. -const Map> kDdcDartSdkJsMapArtifactMap = >{ - WebRendererMode.auto: { - NullSafetyMode.sound: HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSoundSdkSourcemaps, - NullSafetyMode.unsound: HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSdkSourcemaps, +const Map> + kDdcDartSdkJsMapArtifactMap = + >{ + WebRendererMode.auto: { + NullSafetyMode.sound: + HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSoundSdkSourcemaps, + NullSafetyMode.unsound: + HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSdkSourcemaps, }, - WebRendererMode.canvaskit: { - NullSafetyMode.sound: HostArtifact.webPrecompiledDdcCanvaskitSoundSdkSourcemaps, - NullSafetyMode.unsound: HostArtifact.webPrecompiledDdcCanvaskitSdkSourcemaps, + WebRendererMode.canvaskit: { + NullSafetyMode.sound: + HostArtifact.webPrecompiledDdcCanvaskitSoundSdkSourcemaps, + NullSafetyMode.unsound: + HostArtifact.webPrecompiledDdcCanvaskitSdkSourcemaps, }, - WebRendererMode.html: { + WebRendererMode.html: { NullSafetyMode.sound: HostArtifact.webPrecompiledDdcSoundSdkSourcemaps, NullSafetyMode.unsound: HostArtifact.webPrecompiledDdcSdkSourcemaps, }, diff --git a/packages/flutter_tools/lib/src/web/web_runner.dart b/packages/flutter_tools/lib/src/web/web_runner.dart index 6cf020bd849..af7424a3b71 100644 --- a/packages/flutter_tools/lib/src/web/web_runner.dart +++ b/packages/flutter_tools/lib/src/web/web_runner.dart @@ -33,7 +33,6 @@ abstract class WebRunnerFactory { required SystemClock systemClock, required Usage usage, required Analytics analytics, - required bool useImplicitPubspecResolution, bool machine = false, }); } diff --git a/packages/flutter_tools/lib/src/windows/build_windows.dart b/packages/flutter_tools/lib/src/windows/build_windows.dart index c614c64b4e9..e17a6faefba 100644 --- a/packages/flutter_tools/lib/src/windows/build_windows.dart +++ b/packages/flutter_tools/lib/src/windows/build_windows.dart @@ -157,11 +157,9 @@ Future buildWindows( 'A summary of your Windows bundle analysis can be found at: ${outputFile.path}', ); - // DevTools expects a file path relative to the .flutter-devtools/ dir. - final String relativeAppSizePath = outputFile.path.split('.flutter-devtools/').last.trim(); globals.printStatus( '\nTo analyze your app size in Dart DevTools, run the following command:\n' - 'dart devtools --appSizeBase=$relativeAppSizePath' + 'dart devtools --appSizeBase=${outputFile.path}' ); } } diff --git a/packages/flutter_tools/lib/src/xcode_project.dart b/packages/flutter_tools/lib/src/xcode_project.dart index eaa3237031e..f411a015240 100644 --- a/packages/flutter_tools/lib/src/xcode_project.dart +++ b/packages/flutter_tools/lib/src/xcode_project.dart @@ -5,15 +5,18 @@ import 'base/error_handling_io.dart'; import 'base/file_system.dart'; import 'base/utils.dart'; +import 'base/version.dart'; import 'build_info.dart'; import 'bundle.dart' as bundle; import 'convert.dart'; +import 'features.dart'; import 'flutter_plugins.dart'; import 'globals.dart' as globals; import 'ios/code_signing.dart'; import 'ios/plist_parser.dart'; import 'ios/xcode_build_settings.dart' as xcode; import 'ios/xcodeproj.dart'; +import 'macos/xcode.dart'; import 'platform_plugins.dart'; import 'project.dart'; import 'template.dart'; @@ -147,6 +150,40 @@ abstract class XcodeBasedProject extends FlutterProjectPlatform { .contains('FlutterGeneratedPluginSwiftPackage'); } + /// True if this project doesn't have Swift Package Manager disabled in the + /// pubspec, has either an iOS or macOS platform implementation, is not a + /// module project, Xcode is 15 or greater, and the Swift Package Manager + /// feature is enabled. + bool get usesSwiftPackageManager { + if (!featureFlags.isSwiftPackageManagerEnabled) { + return false; + } + + // The project can disable Swift Package Manager in its pubspec.yaml. + if (parent.manifest.disabledSwiftPackageManager) { + return false; + } + + // TODO(loic-sharma): Support Swift Package Manager in add-to-app modules. + // https://github.com/flutter/flutter/issues/146957 + if (parent.isModule) { + return false; + } + + if (!existsSync()) { + return false; + } + + // Swift Package Manager requires Xcode 15 or greater. + final Xcode? xcode = globals.xcode; + final Version? xcodeVersion = xcode?.currentVersion; + if (xcodeVersion == null || xcodeVersion.major < 15) { + return false; + } + + return true; + } + Future projectInfo() async { final XcodeProjectInterpreter? xcodeProjectInterpreter = globals.xcodeProjectInterpreter; if (!xcodeProject.existsSync() || xcodeProjectInterpreter == null || !xcodeProjectInterpreter.isInstalled) { diff --git a/packages/flutter_tools/pubspec.yaml b/packages/flutter_tools/pubspec.yaml index b314a6fb329..22ede47a29f 100644 --- a/packages/flutter_tools/pubspec.yaml +++ b/packages/flutter_tools/pubspec.yaml @@ -3,7 +3,7 @@ description: Tools for building Flutter applications homepage: https://flutter.dev environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: # To update these, use "flutter update-packages --force-upgrade". diff --git a/packages/flutter_tools/templates/app_shared/android-kotlin.tmpl/app/src/main/kotlin/androidIdentifier/MainActivity.kt.tmpl b/packages/flutter_tools/templates/app_shared/android-kotlin.tmpl/app/src/main/kotlin/androidIdentifier/MainActivity.kt.tmpl index a4d9fd335f4..7c51a726669 100644 --- a/packages/flutter_tools/templates/app_shared/android-kotlin.tmpl/app/src/main/kotlin/androidIdentifier/MainActivity.kt.tmpl +++ b/packages/flutter_tools/templates/app_shared/android-kotlin.tmpl/app/src/main/kotlin/androidIdentifier/MainActivity.kt.tmpl @@ -2,4 +2,4 @@ package {{androidIdentifier}} import io.flutter.embedding.android.FlutterActivity -class MainActivity: FlutterActivity() +class MainActivity : FlutterActivity() diff --git a/packages/flutter_tools/templates/app_shared/ios-objc.tmpl/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme.tmpl b/packages/flutter_tools/templates/app_shared/ios-objc.tmpl/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme.tmpl index 542e2ae7000..1d77702a1c1 100644 --- a/packages/flutter_tools/templates/app_shared/ios-objc.tmpl/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme.tmpl +++ b/packages/flutter_tools/templates/app_shared/ios-objc.tmpl/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme.tmpl @@ -79,6 +79,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/packages/flutter_tools/templates/app_shared/ios-swift.tmpl/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme.tmpl b/packages/flutter_tools/templates/app_shared/ios-swift.tmpl/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme.tmpl index 844b54e6c06..a06d9ff3547 100644 --- a/packages/flutter_tools/templates/app_shared/ios-swift.tmpl/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme.tmpl +++ b/packages/flutter_tools/templates/app_shared/ios-swift.tmpl/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme.tmpl @@ -79,6 +79,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/packages/flutter_tools/templates/app_shared/macos.tmpl/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme.tmpl b/packages/flutter_tools/templates/app_shared/macos.tmpl/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme.tmpl index 9f7b8459b63..27e6bdbefa3 100644 --- a/packages/flutter_tools/templates/app_shared/macos.tmpl/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme.tmpl +++ b/packages/flutter_tools/templates/app_shared/macos.tmpl/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme.tmpl @@ -79,6 +79,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> diff --git a/packages/flutter_tools/templates/module/android/gradle/build.gradle.tmpl b/packages/flutter_tools/templates/module/android/gradle/build.gradle.tmpl index f2c623cc887..66f4f1c271d 100644 --- a/packages/flutter_tools/templates/module/android/gradle/build.gradle.tmpl +++ b/packages/flutter_tools/templates/module/android/gradle/build.gradle.tmpl @@ -1,18 +1,5 @@ // Generated file. Do not edit. -buildscript { - ext.kotlin_version = "{{kotlinVersion}}" - repositories { - google() - mavenCentral() - } - - dependencies { - classpath("com.android.tools.build:gradle:{{agpVersionForModule}}") - classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version") - } -} - allprojects { repositories { google() @@ -31,7 +18,3 @@ android { targetSdk = {{targetSdkVersion}} } } - -dependencies { - implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version") -} diff --git a/packages/flutter_tools/templates/module/android/host_app_ephemeral/settings.gradle.copy.tmpl b/packages/flutter_tools/templates/module/android/host_app_ephemeral/settings.gradle.copy.tmpl index b40f9f78178..4498ec041eb 100644 --- a/packages/flutter_tools/templates/module/android/host_app_ephemeral/settings.gradle.copy.tmpl +++ b/packages/flutter_tools/templates/module/android/host_app_ephemeral/settings.gradle.copy.tmpl @@ -1,4 +1,29 @@ // Generated file. Do not edit. + +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() + } +} + +plugins { + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.library" version "8.7.0" apply false + id "org.jetbrains.kotlin.android" version "1.8.22" apply false +} + include ':app' rootProject.name = 'android_generated' diff --git a/packages/flutter_tools/templates/module/android/library_new_embedding/Flutter.tmpl/build.gradle.tmpl b/packages/flutter_tools/templates/module/android/library_new_embedding/Flutter.tmpl/build.gradle.tmpl index 9a10bea781f..128634409ee 100644 --- a/packages/flutter_tools/templates/module/android/library_new_embedding/Flutter.tmpl/build.gradle.tmpl +++ b/packages/flutter_tools/templates/module/android/library_new_embedding/Flutter.tmpl/build.gradle.tmpl @@ -1,5 +1,10 @@ // Generated file. Do not edit. +plugins { + id "com.android.library" + id "dev.flutter.flutter-gradle-plugin" +} + def localProperties = new Properties() def localPropertiesFile = new File(buildscript.sourceFile.parentFile.parentFile, "local.properties") if (localPropertiesFile.exists()) { @@ -8,11 +13,6 @@ if (localPropertiesFile.exists()) { } } -def flutterRoot = localProperties.getProperty("flutter.sdk") -if (flutterRoot == null) { - throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") -} - def flutterVersionCode = localProperties.getProperty("flutter.versionCode") if (flutterVersionCode == null) { flutterVersionCode = "1" @@ -23,9 +23,6 @@ if (flutterVersionName == null) { flutterVersionName = "1.0" } -apply plugin: "com.android.library" -apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" - group = "{{androidIdentifier}}" version = "1.0" diff --git a/packages/flutter_tools/templates/module/android/library_new_embedding/include_flutter.groovy.copy.tmpl b/packages/flutter_tools/templates/module/android/library_new_embedding/include_flutter.groovy.copy.tmpl index 181d08ba6da..3f6992279a9 100644 --- a/packages/flutter_tools/templates/module/android/library_new_embedding/include_flutter.groovy.copy.tmpl +++ b/packages/flutter_tools/templates/module/android/library_new_embedding/include_flutter.groovy.copy.tmpl @@ -26,3 +26,7 @@ localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } def flutterSdkPath = properties.getProperty("flutter.sdk") assert flutterSdkPath != null, "flutter.sdk not set in local.properties" gradle.apply from: "$flutterSdkPath/packages/flutter_tools/gradle/module_plugin_loader.gradle" + +gradle.pluginManagement{ + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") +} diff --git a/packages/flutter_tools/templates/plugin_shared/pubspec.yaml.tmpl b/packages/flutter_tools/templates/plugin_shared/pubspec.yaml.tmpl index 0b755b1d285..3fc81ef83c3 100644 --- a/packages/flutter_tools/templates/plugin_shared/pubspec.yaml.tmpl +++ b/packages/flutter_tools/templates/plugin_shared/pubspec.yaml.tmpl @@ -13,7 +13,7 @@ dependencies: {{#web}} flutter_web_plugins: sdk: flutter - web: ^0.5.1 + web: ^1.0.0 {{/web}} plugin_platform_interface: ^2.0.2 diff --git a/packages/flutter_tools/templates/template_manifest.json b/packages/flutter_tools/templates/template_manifest.json index 857c6dcc3ee..62bd63c3f8e 100644 --- a/packages/flutter_tools/templates/template_manifest.json +++ b/packages/flutter_tools/templates/template_manifest.json @@ -372,6 +372,10 @@ "templates/skeleton/test/unit_test.dart.tmpl", "templates/skeleton/test/widget_test.dart.tmpl", + "templates/widget_preview_scaffold/lib/main.dart.tmpl", + "templates/widget_preview_scaffold/pubspec.yaml.tmpl", + "templates/widget_preview_scaffold/README.md.tmpl", + "templates/xcode/ios/custom_application_bundle/Runner.xcworkspace.tmpl/contents.xcworkspacedata", "templates/xcode/ios/custom_application_bundle/Runner.xcworkspace.tmpl/xcshareddata/IDEWorkspaceChecks.plist", "templates/xcode/ios/custom_application_bundle/Runner.xcworkspace.tmpl/xcshareddata/WorkspaceSettings.xcsettings", diff --git a/packages/flutter_tools/templates/widget_preview_scaffold/README.md.tmpl b/packages/flutter_tools/templates/widget_preview_scaffold/README.md.tmpl new file mode 100644 index 00000000000..3648fd7744f --- /dev/null +++ b/packages/flutter_tools/templates/widget_preview_scaffold/README.md.tmpl @@ -0,0 +1,4 @@ +# {{titleCaseProjectName}} + +This project is generated by `flutter widget-preview` and is used to host Widgets +to be previewed in the widget previewer. diff --git a/dev/integration_tests/new_gallery/test/utils.dart b/packages/flutter_tools/templates/widget_preview_scaffold/lib/main.dart.tmpl similarity index 55% rename from dev/integration_tests/new_gallery/test/utils.dart rename to packages/flutter_tools/templates/widget_preview_scaffold/lib/main.dart.tmpl index 9218e2ee8d7..3cba3378351 100644 --- a/dev/integration_tests/new_gallery/test/utils.dart +++ b/packages/flutter_tools/templates/widget_preview_scaffold/lib/main.dart.tmpl @@ -2,5 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// Replace Windows line endings with Unix line endings -String standardizeLineEndings(String str) => str.replaceAll('\r\n', '\n'); +Future main() async { + // TODO(bkonyi): implement. +} diff --git a/packages/flutter_tools/templates/widget_preview_scaffold/pubspec.yaml.tmpl b/packages/flutter_tools/templates/widget_preview_scaffold/pubspec.yaml.tmpl new file mode 100644 index 00000000000..fb82124b138 --- /dev/null +++ b/packages/flutter_tools/templates/widget_preview_scaffold/pubspec.yaml.tmpl @@ -0,0 +1,16 @@ +name: {{projectName}} +description: Scaffolding for Flutter Widget Previews +publish_to: 'none' +version: 0.0.1 + +environment: + sdk: {{dartSdkVersionBounds}} + +dependencies: + flutter: + sdk: flutter + flutter_test: + sdk: flutter + +flutter: + uses-material-design: true diff --git a/packages/flutter_tools/templates/xcode/ios/custom_application_bundle/Runner.xcodeproj.tmpl/xcshareddata/xcschemes/Runner.xcscheme.tmpl b/packages/flutter_tools/templates/xcode/ios/custom_application_bundle/Runner.xcodeproj.tmpl/xcshareddata/xcschemes/Runner.xcscheme.tmpl index e3f914b73fa..fa7bb17d011 100644 --- a/packages/flutter_tools/templates/xcode/ios/custom_application_bundle/Runner.xcodeproj.tmpl/xcshareddata/xcschemes/Runner.xcscheme.tmpl +++ b/packages/flutter_tools/templates/xcode/ios/custom_application_bundle/Runner.xcodeproj.tmpl/xcshareddata/xcschemes/Runner.xcscheme.tmpl @@ -37,6 +37,7 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" + enableGPUValidationMode = "1" allowLocationSimulation = "YES"> =3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 '''); final File dartFile = fileSystem.file(fileSystem.path.join(directory.path, 'lib', 'main.dart')); diff --git a/packages/flutter_tools/test/commands.shard/hermetic/assemble_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/assemble_test.dart index f62d92d9aad..831dcbe05e0 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/assemble_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/assemble_test.dart @@ -94,6 +94,35 @@ void main() { FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); + testUsingContext('flutter assemble sends assemble-deferred-components', () async { + final AssembleCommand command = AssembleCommand( + buildSystem: TestBuildSystem.all(BuildResult(success: true)), + ); + final CommandRunner commandRunner = createTestCommandRunner(command); + await commandRunner.run([ + 'assemble', + '-o Output', + '-dTargetPlatform=android', + '-dBuildMode=release', + 'android_aot_deferred_components_bundle_release_android-arm64', + ]); + expect( + fakeAnalytics.sentEvents, + contains( + Event.flutterBuildInfo( + label: 'assemble-deferred-components', + buildType: 'android', + settings: 'android_aot_deferred_components_bundle_release_android-arm64', + ), + ), + ); + }, overrides: { + Analytics: () => fakeAnalytics, + Cache: () => Cache.test(processManager: FakeProcessManager.any()), + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + }); + testUsingContext('flutter assemble sends usage values correctly with platform', () async { final AssembleCommand command = AssembleCommand( buildSystem: TestBuildSystem.all(BuildResult(success: true))); diff --git a/packages/flutter_tools/test/commands.shard/hermetic/attach_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/attach_test.dart index 47a2d14cdb1..00cfd4f1f6b 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/attach_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/attach_test.dart @@ -30,7 +30,6 @@ import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/reporting/reporting.dart'; import 'package:flutter_tools/src/resident_runner.dart'; import 'package:flutter_tools/src/run_hot.dart'; -import 'package:flutter_tools/src/vmservice.dart'; import 'package:multicast_dns/multicast_dns.dart'; import 'package:test/fake.dart'; import 'package:unified_analytics/unified_analytics.dart'; @@ -1100,7 +1099,7 @@ void main() { bool enableDevTools, ) async { await null; - throw vm_service.RPCError('flutter._listViews', RPCErrorCodes.kServiceDisappeared, ''); + throw vm_service.RPCError('flutter._listViews', vm_service.RPCErrorKind.kServiceDisappeared.code, ''); }; testDeviceManager.devices = [device]; @@ -1139,7 +1138,7 @@ void main() { bool enableDevTools, ) async { await null; - throw vm_service.RPCError('flutter._listViews', RPCErrorCodes.kServerError, 'Service connection disposed'); + throw vm_service.RPCError('flutter._listViews', vm_service.RPCErrorKind.kServerError.code, 'Service connection disposed'); }; testDeviceManager.devices = [device]; @@ -1179,7 +1178,7 @@ void main() { bool enableDevTools, ) async { await null; - throw vm_service.RPCError('flutter._listViews', RPCErrorCodes.kInvalidParams, ''); + throw vm_service.RPCError('flutter._listViews', vm_service.RPCErrorKind.kInvalidParams.code, ''); }; testDeviceManager.devices = [device]; @@ -1259,8 +1258,6 @@ class FakeHotRunnerFactory extends Fake implements HotRunnerFactory { FlutterProject? flutterProject, Analytics? analytics, String? nativeAssetsYamlFile, - HotRunnerNativeAssetsBuilder? nativeAssetsBuilder, - required bool useImplicitPubspecResolution, }) { if (_artifactTester != null) { for (final FlutterDevice device in devices) { diff --git a/packages/flutter_tools/test/commands.shard/hermetic/build_ios_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/build_ios_test.dart index 3f08cd4e89f..359dee3dbda 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/build_ios_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/build_ios_test.dart @@ -17,6 +17,7 @@ import 'package:flutter_tools/src/build_system/build_system.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/build.dart'; import 'package:flutter_tools/src/commands/build_ios.dart'; +import 'package:flutter_tools/src/dart/pub.dart'; import 'package:flutter_tools/src/ios/code_signing.dart'; import 'package:flutter_tools/src/ios/mac.dart'; import 'package:flutter_tools/src/ios/plist_parser.dart'; @@ -28,6 +29,7 @@ import 'package:unified_analytics/unified_analytics.dart'; import '../../general.shard/ios/xcresult_test_data.dart'; import '../../src/common.dart'; import '../../src/context.dart'; +import '../../src/fake_pub_deps.dart'; import '../../src/fakes.dart'; import '../../src/test_build_system.dart'; import '../../src/test_flutter_command_runner.dart'; @@ -114,13 +116,6 @@ void main() { 'xattr', '-r', '-d', 'com.apple.FinderInfo', '/', ]); - const FakeCommand dartPubDepsCommand = FakeCommand(command: [ - 'dart', - 'pub', - 'deps', - '--json', - ]); - FakeCommand setUpRsyncCommand({void Function(List command)? onRun}) { return FakeCommand( command: const [ @@ -305,9 +300,9 @@ void main() { expect(testLogger.statusText, contains(RegExp(r'✓ Built build/ios/iphoneos/Runner\.app \(\d+\.\d+MB\)'))); }, overrides: { FileSystem: () => fileSystem, + Pub: FakePubWithPrimedDeps.new, ProcessManager: () => FakeProcessManager.list([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true); }), @@ -331,7 +326,6 @@ void main() { processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true); }), @@ -345,6 +339,7 @@ void main() { }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -369,7 +364,6 @@ void main() { FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler( disablePortPublication: true, onRun: (_) { @@ -378,6 +372,7 @@ void main() { ), setUpRsyncCommand(), ]), + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -402,7 +397,6 @@ void main() { FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler( onRun: (_) { fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true); @@ -410,6 +404,7 @@ void main() { ), setUpRsyncCommand(), ]), + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -427,7 +422,6 @@ void main() { processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(customNaming: true, onRun: (_) { fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true); }), @@ -446,6 +440,7 @@ void main() { }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -462,7 +457,6 @@ void main() { ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(deviceId: '1234', onRun: (_) { fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true); }), @@ -477,6 +471,7 @@ void main() { }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -493,7 +488,6 @@ void main() { ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(simulator: true, onRun: (_) { fileSystem.directory('build/ios/Debug-iphonesimulator/Runner.app').createSync(recursive: true); }), @@ -507,6 +501,7 @@ void main() { }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -524,7 +519,6 @@ void main() { createMinimalMockProjectFiles(); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(verbose: true, onRun: (_) { fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true); }), @@ -537,6 +531,7 @@ void main() { }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -553,7 +548,6 @@ void main() { ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true); fileSystem.file('build/flutter_size_01/snapshot.arm64.json') @@ -591,6 +585,7 @@ void main() { Logger: () => logger, ProcessManager: () => processManager, Platform: () => macosPlatform, + Pub: FakePubWithPrimedDeps.new, FileSystemUtils: () => FileSystemUtils(fileSystem: fileSystem, platform: macosPlatform), Analytics: () => fakeAnalytics, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), @@ -640,7 +635,6 @@ void main() { FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.directory('build/ios/Release-iphoneos/Runner.app') .createSync(recursive: true); @@ -656,6 +650,7 @@ void main() { platform: macosPlatform, ), XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), + Pub: FakePubWithPrimedDeps.new, Analytics: () => fakeAnalytics, }); @@ -695,7 +690,6 @@ void main() { FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.directory('build/ios/Release-iphoneos/Runner.app') .createSync(recursive: true); @@ -722,6 +716,7 @@ void main() { plutilCommand, plutilCommand, plutilCommand, ]), ), + Pub: FakePubWithPrimedDeps.new, Analytics: () => fakeAnalytics, }); }); @@ -739,7 +734,6 @@ void main() { ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); }), @@ -759,6 +753,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -775,7 +770,6 @@ void main() { ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); }, stdout: 'Lots of spew from Xcode', @@ -799,6 +793,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -815,7 +810,6 @@ void main() { ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); }), @@ -838,6 +832,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -854,7 +849,6 @@ void main() { ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(exitCode: 1), setUpXCResultCommand(stdout: kSampleResultJsonWithIssues), setUpRsyncCommand(), @@ -871,6 +865,7 @@ void main() { }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -887,7 +882,6 @@ void main() { ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); }), @@ -911,6 +905,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -927,7 +922,6 @@ void main() { ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler( exitCode: 1, onRun: (_) { @@ -951,6 +945,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -967,7 +962,6 @@ void main() { ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); }), @@ -987,6 +981,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1003,7 +998,6 @@ void main() { ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, // Intentionally fail the first xcodebuild command with concurrent run failure message. setUpFakeXcodeBuildHandler( exitCode: 1, @@ -1035,6 +1029,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1051,7 +1046,6 @@ void main() { ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler( exitCode: 1, stdout: ''' @@ -1077,6 +1071,7 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1093,7 +1088,6 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler( exitCode: 1, onRun: (_) { @@ -1116,6 +1110,7 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(developmentTeam: null), }); @@ -1143,7 +1138,6 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler( exitCode: 1, stdout: ''' @@ -1156,6 +1150,7 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig setUpXCResultCommand(stdout: kSampleResultJsonNoIssues), setUpRsyncCommand(), ]), + Pub: FakePubWithPrimedDeps.new, EnvironmentType: () => EnvironmentType.physical, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), @@ -1173,7 +1168,6 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler( exitCode: 1, onRun: (_) { @@ -1195,6 +1189,7 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(developmentTeam: null), }); @@ -1211,7 +1206,6 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler( exitCode: 1, onRun: (_) { @@ -1235,6 +1229,7 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(developmentTeam: null), }); @@ -1251,7 +1246,6 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler( exitCode: 1, onRun: (_) { @@ -1275,6 +1269,7 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(developmentTeam: null), }); @@ -1293,7 +1288,6 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler( simulator: true, exitCode: 1, @@ -1317,6 +1311,7 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1333,7 +1328,6 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler( simulator: true, exitCode: 1, @@ -1358,6 +1352,7 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1375,7 +1370,6 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler( simulator: true, exitCode: 1, @@ -1402,6 +1396,7 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1418,7 +1413,6 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig ); processManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler( simulator: true, exitCode: 1, @@ -1439,6 +1433,7 @@ Runner requires a provisioning profile. Select a provisioning profile in the Sig FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); diff --git a/packages/flutter_tools/test/commands.shard/hermetic/build_ipa_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/build_ipa_test.dart index 0d8917642c0..8413124a8ef 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/build_ipa_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/build_ipa_test.dart @@ -16,6 +16,7 @@ import 'package:flutter_tools/src/build_system/build_system.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/build.dart'; import 'package:flutter_tools/src/commands/build_ios.dart'; +import 'package:flutter_tools/src/dart/pub.dart'; import 'package:flutter_tools/src/ios/plist_parser.dart'; import 'package:flutter_tools/src/ios/xcodeproj.dart'; import 'package:test/fake.dart'; @@ -25,6 +26,7 @@ import '../../general.shard/ios/xcresult_test_data.dart'; import '../../src/common.dart'; import '../../src/context.dart'; import '../../src/fake_process_manager.dart'; +import '../../src/fake_pub_deps.dart'; import '../../src/fakes.dart'; import '../../src/test_build_system.dart'; import '../../src/test_flutter_command_runner.dart'; @@ -140,13 +142,6 @@ void main() { 'xattr', '-r', '-d', 'com.apple.FinderInfo', '/', ]); - const FakeCommand dartPubDepsCommand = FakeCommand(command: [ - 'dart', - 'pub', - 'deps', - '--json', - ]); - FakeCommand setUpXCResultCommand({String stdout = '', void Function(List command)? onRun}) { return FakeCommand( command: const [ @@ -405,7 +400,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(), exportArchiveCommand(exportOptionsPlist: _exportOptionsPlist), ]); @@ -420,6 +414,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -437,7 +432,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(), exportArchiveCommand(exportOptionsPlist: _exportOptionsPlist, cachePlist: cachedExportOptionsPlist), ]); @@ -467,6 +461,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(version: Version(15, 4, null)), }); @@ -484,7 +479,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(), exportArchiveCommand(exportOptionsPlist: _exportOptionsPlist, cachePlist: cachedExportOptionsPlist), ]); @@ -514,6 +508,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(version: Version(15, 4, null)), }); @@ -531,7 +526,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(), exportArchiveCommand(exportOptionsPlist: _exportOptionsPlist, cachePlist: cachedExportOptionsPlist), ]); @@ -561,6 +555,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(version: Version(15, 4, null)), }); @@ -577,7 +572,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(), exportArchiveCommand(exportOptionsPlist: _exportOptionsPlist), ]); @@ -590,6 +584,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(version: Version(15, 3, null)), }); @@ -607,7 +602,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(), exportArchiveCommand(exportOptionsPlist: _exportOptionsPlist, cachePlist: cachedExportOptionsPlist), ]); @@ -637,6 +631,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(version: Version(15, 4, null)), }); @@ -653,7 +648,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(), exportArchiveCommand(exportOptionsPlist: _exportOptionsPlist), ]); @@ -666,6 +660,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(version: Version(15, 3, null)), }); @@ -682,7 +677,6 @@ void main() { fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(), exportArchiveCommand(exportOptionsPlist: exportOptions.path), ]); @@ -705,6 +699,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), PlistParser: () => plistUtils, @@ -722,7 +717,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(), const FakeCommand( command: [ @@ -761,6 +755,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -778,7 +773,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(), exportArchiveCommand( exportOptionsPlist: _exportOptionsPlist, @@ -796,6 +790,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -813,7 +808,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(), exportArchiveCommand(exportOptionsPlist: _exportOptionsPlist, cachePlist: cachedExportOptionsPlist), ]); @@ -849,6 +843,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -866,7 +861,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(), exportArchiveCommand(exportOptionsPlist: _exportOptionsPlist, cachePlist: cachedExportOptionsPlist), ]); @@ -902,6 +896,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -919,7 +914,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(), exportArchiveCommand(exportOptionsPlist: _exportOptionsPlist, cachePlist: cachedExportOptionsPlist), ]); @@ -955,6 +949,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -971,7 +966,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(verbose: true), exportArchiveCommand(exportOptionsPlist: _exportOptionsPlist), ]); @@ -985,6 +979,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1001,7 +996,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(), exportArchiveCommand(exportOptionsPlist: _exportOptionsPlist), ]); @@ -1014,6 +1008,7 @@ void main() { }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1030,7 +1025,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, const FakeCommand( command: [ 'xcrun', @@ -1067,6 +1061,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1083,7 +1078,6 @@ void main() { ); createMinimalMockProjectFiles(); - fakeProcessManager.addCommand(dartPubDepsCommand); fakeProcessManager.addCommand(setUpFakeXcodeBuildHandler()); await expectToolExitLater( createTestCommandRunner(command).run( @@ -1094,6 +1088,7 @@ void main() { }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1115,7 +1110,6 @@ void main() { ..writeAsBytesSync(List.generate(10000, (int index) => 0)); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.file('build/flutter_size_01/snapshot.arm64.json') ..createSync(recursive: true) @@ -1149,6 +1143,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, FileSystemUtils: () => FileSystemUtils(fileSystem: fileSystem, platform: macosPlatform), Analytics: () => fakeAnalytics, @@ -1171,7 +1166,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(), exportArchiveCommand(), ]); @@ -1193,6 +1187,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1209,7 +1204,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleFilePath).createSync(); }), @@ -1228,6 +1222,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1244,7 +1239,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleFilePath).createSync(); }), @@ -1264,6 +1258,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1280,7 +1275,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleFilePath).createSync(); }), @@ -1302,6 +1296,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1318,7 +1313,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(exitCode: 1), ]); createMinimalMockProjectFiles(); @@ -1334,6 +1328,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1351,7 +1346,6 @@ void main() { ); fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleFilePath).createSync(); }), @@ -1374,6 +1368,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1384,7 +1379,6 @@ void main() { const String plistPath = 'build/ios/archive/Runner.xcarchive/Products/Applications/Runner.app/Info.plist'; fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.file(plistPath).createSync(recursive: true); }), @@ -1428,6 +1422,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), PlistParser: () => plistUtils, @@ -1438,7 +1433,6 @@ void main() { const String plistPath = 'build/ios/archive/Runner.xcarchive/Products/Applications/Runner.app/Info.plist'; fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.file(plistPath).createSync(recursive: true); }), @@ -1488,6 +1482,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), PlistParser: () => plistUtils, @@ -1498,7 +1493,6 @@ void main() { const String plistPath = 'build/ios/archive/Runner.xcarchive/Products/Applications/Runner.app/Info.plist'; fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.file(plistPath).createSync(recursive: true); }), @@ -1547,6 +1541,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), PlistParser: () => plistUtils, @@ -1558,7 +1553,6 @@ void main() { const String plistPath = 'build/ios/archive/Runner.xcarchive/Products/Applications/Runner.app/Info.plist'; fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.file(plistPath).createSync(recursive: true); }), @@ -1592,6 +1586,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), PlistParser: () => plistUtils, @@ -1602,7 +1597,6 @@ void main() { const String plistPath = 'build/ios/archive/Runner.xcarchive/Products/Applications/Runner.app/Info.plist'; fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.file(plistPath).createSync(recursive: true); }), @@ -1636,6 +1630,7 @@ void main() { Logger: () => logger, ProcessManager: () => fakeProcessManager, Platform: () => macosPlatform, + Pub: FakePubWithPrimedDeps.new, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), PlistParser: () => plistUtils, }); @@ -1649,7 +1644,6 @@ void main() { fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.file(templateIconContentsJsonPath) ..createSync(recursive: true) @@ -1720,6 +1714,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1732,7 +1727,6 @@ void main() { fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.file(templateIconContentsJsonPath) ..createSync(recursive: true) @@ -1803,6 +1797,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1813,7 +1808,6 @@ void main() { fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.file(projectIconContentsJsonPath) ..createSync(recursive: true) @@ -1866,6 +1860,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1876,7 +1871,6 @@ void main() { fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.file(projectIconContentsJsonPath) ..createSync(recursive: true) @@ -1930,6 +1924,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -1940,7 +1935,6 @@ void main() { fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.file(projectIconContentsJsonPath) ..createSync(recursive: true) @@ -1993,6 +1987,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -2003,7 +1998,6 @@ void main() { fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { // Uses unknown format version 123. fileSystem.file(projectIconContentsJsonPath) @@ -2059,6 +2053,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -2076,7 +2071,6 @@ void main() { fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { // The following json contains examples of: // - invalid size @@ -2170,6 +2164,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -2182,7 +2177,6 @@ void main() { fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.file(templateLaunchImageContentsJsonPath) ..createSync(recursive: true) @@ -2251,6 +2245,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); @@ -2264,7 +2259,6 @@ void main() { fakeProcessManager.addCommands([ xattrCommand, - dartPubDepsCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.file(templateLaunchImageContentsJsonPath) ..createSync(recursive: true) @@ -2333,6 +2327,7 @@ void main() { FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => fakeProcessManager, + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); diff --git a/packages/flutter_tools/test/commands.shard/hermetic/build_macos_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/build_macos_test.dart index bf14c0c0e4d..9536def2cd9 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/build_macos_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/build_macos_test.dart @@ -17,6 +17,7 @@ import 'package:flutter_tools/src/build_system/build_system.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/build.dart'; import 'package:flutter_tools/src/commands/build_macos.dart'; +import 'package:flutter_tools/src/dart/pub.dart'; import 'package:flutter_tools/src/features.dart'; import 'package:flutter_tools/src/ios/xcodeproj.dart'; import 'package:flutter_tools/src/project.dart'; @@ -25,6 +26,7 @@ import 'package:unified_analytics/unified_analytics.dart'; import '../../src/common.dart'; import '../../src/context.dart'; import '../../src/fake_process_manager.dart'; +import '../../src/fake_pub_deps.dart'; import '../../src/fakes.dart'; import '../../src/test_build_system.dart'; import '../../src/test_flutter_command_runner.dart'; @@ -105,20 +107,13 @@ void main() { createCoreMockProjectFiles(); } - const FakeCommand dartPubDepsCommand = FakeCommand(command: [ - 'dart', - 'pub', - 'deps', - '--json', - ]); - // Creates a FakeCommand for the xcodebuild call to build the app // in the given configuration. FakeCommand setUpFakeXcodeBuildHandler( String configuration, { bool verbose = false, void Function(List command)? onRun, - List? additionalCommandArguements, + List? additionalCommandArguments, }) { final FlutterProject flutterProject = FlutterProject.fromDirectory(fileSystem.currentDirectory); final Directory flutterBuildDir = fileSystem.directory(getMacOSBuildDirectory()); @@ -139,8 +134,8 @@ void main() { else '-quiet', 'COMPILER_INDEX_STORE_ENABLE=NO', - if (additionalCommandArguements != null) - ...additionalCommandArguements, + if (additionalCommandArguments != null) + ...additionalCommandArguments, ], stdout: ''' STDOUT STUFF @@ -225,6 +220,7 @@ STDERR STUFF Platform: () => macosPlatform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), + Pub: FakePubWithPrimedDeps.new, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), Analytics: () => fakeAnalytics, }); @@ -307,9 +303,9 @@ STDERR STUFF }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ - dartPubDepsCommand, setUpFakeXcodeBuildHandler('Debug'), ]), + Pub: FakePubWithPrimedDeps.new, Platform: () => macosPlatform, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); @@ -333,10 +329,10 @@ STDERR STUFF }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ - dartPubDepsCommand, setUpFakeXcodeBuildHandler('Release'), ]), Platform: () => macosPlatform, + Pub: FakePubWithPrimedDeps.new, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); @@ -358,10 +354,10 @@ STDERR STUFF }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ - dartPubDepsCommand, setUpFakeXcodeBuildHandler('Debug'), ]), Platform: () => macosPlatform, + Pub: FakePubWithPrimedDeps.new, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); @@ -383,10 +379,10 @@ STDERR STUFF }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ - dartPubDepsCommand, setUpFakeXcodeBuildHandler('Debug', verbose: true), ]), Platform: () => macosPlatform, + Pub: FakePubWithPrimedDeps.new, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); @@ -409,10 +405,10 @@ STDERR STUFF }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ - dartPubDepsCommand, setUpFakeXcodeBuildHandler('Profile'), ]), Platform: () => macosPlatform, + Pub: FakePubWithPrimedDeps.new, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithProfile(), FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); @@ -435,10 +431,10 @@ STDERR STUFF }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ - dartPubDepsCommand, setUpFakeXcodeBuildHandler('Release'), ]), Platform: () => macosPlatform, + Pub: FakePubWithPrimedDeps.new, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); @@ -499,10 +495,10 @@ STDERR STUFF }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ - dartPubDepsCommand, setUpFakeXcodeBuildHandler('Release'), ]), Platform: () => macosPlatform, + Pub: FakePubWithPrimedDeps.new, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), Artifacts: () => Artifacts.test(), }); @@ -518,7 +514,6 @@ STDERR STUFF createMinimalMockProjectFiles(); fakeProcessManager.addCommands([ - dartPubDepsCommand, FakeCommand( command: [ '/usr/bin/env', @@ -557,6 +552,7 @@ STDERR STUFF FileSystem: () => fileSystem, ProcessManager: () => fakeProcessManager, Platform: () => macosPlatformCustomEnv, + Pub: FakePubWithPrimedDeps.new, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), XcodeProjectInterpreter: () => xcodeProjectInterpreter, }); @@ -592,10 +588,10 @@ STDERR STUFF }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ - dartPubDepsCommand, setUpFakeXcodeBuildHandler('Debug'), ]), Platform: () => macosPlatform, + Pub: FakePubWithPrimedDeps.new, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); @@ -664,11 +660,11 @@ STDERR STUFF }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ - dartPubDepsCommand, // we never generate code size snapshot here setUpFakeXcodeBuildHandler('Release'), ]), Platform: () => macosPlatform, + Pub: FakePubWithPrimedDeps.new, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), FileSystemUtils: () => FileSystemUtils(fileSystem: fileSystem, platform: macosPlatform), Analytics: () => fakeAnalytics, @@ -699,7 +695,6 @@ STDERR STUFF }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ - dartPubDepsCommand, // These are generated by gen_snapshot because flutter assemble passes // extra flags specifying this output path setUpFakeXcodeBuildHandler('Release', onRun: (_) { @@ -720,6 +715,7 @@ STDERR STUFF }), ]), Platform: () => macosPlatform, + Pub: FakePubWithPrimedDeps.new, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), FileSystemUtils: () => FileSystemUtils(fileSystem: fileSystem, platform: macosPlatform), Analytics: () => fakeAnalytics, @@ -771,10 +767,9 @@ STDERR STUFF }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ - dartPubDepsCommand, setUpFakeXcodeBuildHandler( 'Debug', - additionalCommandArguements: [ + additionalCommandArguments: [ 'CODE_SIGN_ENTITLEMENTS=/.tmp_rand0/flutter_disable_sandbox_entitlement.rand0/DebugProfileWithDisabledSandboxing.entitlements', ], ), @@ -787,6 +782,7 @@ STDERR STUFF 'LUCI_CI': 'True' } ), + Pub: FakePubWithPrimedDeps.new, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); @@ -840,10 +836,9 @@ STDERR STUFF }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ - dartPubDepsCommand, setUpFakeXcodeBuildHandler( 'Release', - additionalCommandArguements: [ + additionalCommandArguments: [ 'CODE_SIGN_ENTITLEMENTS=/.tmp_rand0/flutter_disable_sandbox_entitlement.rand0/ReleaseWithDisabledSandboxing.entitlements', ], ), @@ -856,6 +851,7 @@ STDERR STUFF 'LUCI_CI': 'True' } ), + Pub: FakePubWithPrimedDeps.new, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); } diff --git a/packages/flutter_tools/test/commands.shard/hermetic/build_web_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/build_web_test.dart index f65259c27b9..84661ace676 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/build_web_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/build_web_test.dart @@ -371,7 +371,7 @@ void main() { 'build', 'web', '--no-pub', - '--web-renderer=${webRenderer.name}', + ...webRenderer.toCliDartDefines, ]); } on ToolExit catch (error) { expect(error, isA()); @@ -402,12 +402,6 @@ void main() { expect(command.usage, contains(option)); } - void expectHidden(String option) { - expect(command.argParser.options.keys, contains(option)); - expect(command.argParser.options[option]!.hide, isTrue); - expect(command.usage, isNot(contains(option))); - } - expectVisible('pwa-strategy'); expectVisible('web-resources-cdn'); expectVisible('optimization-level'); @@ -419,8 +413,6 @@ void main() { expectVisible('wasm'); expectVisible('strip-wasm'); expectVisible('base-href'); - - expectHidden('web-renderer'); }, overrides: { Platform: () => fakePlatform, FileSystem: () => fileSystem, diff --git a/packages/flutter_tools/test/commands.shard/hermetic/daemon_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/daemon_test.dart index 11922609f57..4f998d84739 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/daemon_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/daemon_test.dart @@ -99,7 +99,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); daemonStreams.inputs.add(DaemonMessage({'id': 0, 'method': 'daemon.version'})); final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere(_notEvent); @@ -112,7 +111,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); // Use the flutter_gallery project which has a known set of supported platforms. final String projectPath = globals.fs.path.join(getFlutterRoot(), 'dev', 'integration_tests', 'flutter_gallery'); @@ -217,7 +215,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); globals.printError('daemon.logMessage test'); final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere((DaemonMessage message) { @@ -236,7 +233,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); globals.printWarning('daemon.logMessage test'); final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere((DaemonMessage message) { @@ -257,7 +253,6 @@ void main() { daemonConnection, notifyingLogger: notifyingLogger, logToStdout: true, - useImplicitPubspecResolution: true, ); globals.printStatus('daemon.logMessage test'); return Future.value(); @@ -274,7 +269,6 @@ void main() { daemonConnection, notifyingLogger: notifyingLogger, logToStdout: true, - useImplicitPubspecResolution: true, ); globals.printBox('This is the box message', title: 'Sample title'); return Future.value(); @@ -289,7 +283,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); notifyingLogger.notifyVerbose = false; globals.printTrace('daemon.logMessage test 1'); @@ -311,7 +304,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); expect(notifyingLogger.notifyVerbose, false); @@ -330,7 +322,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); notifyingLogger.notifyVerbose = false; @@ -349,7 +340,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); daemonStreams.inputs.add(DaemonMessage({'id': 0, 'method': 'daemon.shutdown'})); return daemon.onExit.then((int code) async { @@ -362,7 +352,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); daemonStreams.inputs.add(DaemonMessage({'id': 0, 'method': 'app.restart'})); @@ -375,7 +364,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); daemonStreams.inputs.add(DaemonMessage({ @@ -394,7 +382,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); daemonStreams.inputs.add(DaemonMessage({'id': 0, 'method': 'app.stop'})); @@ -407,7 +394,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); daemonStreams.inputs.add(DaemonMessage({'id': 0, 'method': 'device.getDevices'})); final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere(_notEvent); @@ -419,7 +405,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery(); daemon.deviceDomain.addDeviceDiscoverer(discoverer); @@ -436,7 +421,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery(); @@ -450,7 +434,6 @@ void main() { previewBinary: fs.file(r'preview_device.exe'), artifacts: Artifacts.test(fileSystem: fs), builderFactory: () => throw UnimplementedError('TODO implement builder factory'), - useImplicitPubspecResolution: true, )); final List> names = >[]; @@ -521,7 +504,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); daemonStreams.inputs.add(DaemonMessage({'id': 0, 'method': 'device.discoverDevices'})); final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere(_notEvent); @@ -533,7 +515,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery(); daemon.deviceDomain.addDeviceDiscoverer(discoverer); @@ -551,7 +532,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery(); daemon.deviceDomain.addDeviceDiscoverer(discoverer); @@ -576,7 +556,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery(); daemon.deviceDomain.addDeviceDiscoverer(discoverer); @@ -628,7 +607,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery(); daemon.deviceDomain.addDeviceDiscoverer(discoverer); @@ -695,7 +673,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery(); daemon.deviceDomain.addDeviceDiscoverer(discoverer); @@ -755,7 +732,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); final FakePollingDeviceDiscovery discoverer1 = FakePollingDeviceDiscovery(); discoverer1.diagnostics = ['fake diagnostic 1', 'fake diagnostic 2']; @@ -781,7 +757,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); daemonStreams.inputs.add(DaemonMessage({'id': 0, 'method': 'emulator.launch'})); @@ -794,7 +769,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); final Map params = {'emulatorId': 'device', 'coldBoot': 1}; daemonStreams.inputs.add(DaemonMessage({'id': 0, 'method': 'emulator.launch', 'params': params})); @@ -807,7 +781,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); daemonStreams.inputs.add(DaemonMessage({'id': 0, 'method': 'emulator.getEmulators'})); final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere(_notEvent); @@ -822,7 +795,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); // Respond to any requests from the daemon to expose a URL. @@ -842,7 +814,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); daemonStreams.inputs.add(DaemonMessage({'id': 0, 'method': 'devtools.serve'})); @@ -859,7 +830,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); daemonStreams.inputs.add(DaemonMessage({'id': 0, 'method': 'devtools.serve'})); @@ -890,7 +860,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); daemonStreams.inputs.add(DaemonMessage({'id': 0, 'method': 'proxy.connect', 'params': {'port': 123}})); @@ -951,7 +920,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); daemonStreams.inputs.add(DaemonMessage({'id': 0, 'method': 'proxy.connect', 'params': {'port': 123}})); @@ -972,7 +940,6 @@ void main() { daemon = Daemon( daemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); daemonStreams.inputs.add(DaemonMessage({'id': 0, 'method': 'proxy.connect', 'params': {'port': 123}})); @@ -1295,12 +1262,6 @@ class FakeDeviceLogReader implements DeviceLogReader { final StreamController logLinesController = StreamController(); bool disposeCalled = false; - @override - int? appPid; - - @override - FlutterVmService? connectedVMService; - @override void dispose() { disposeCalled = true; @@ -1312,6 +1273,8 @@ class FakeDeviceLogReader implements DeviceLogReader { @override String get name => 'device'; + @override + Future provideVmService(FlutterVmService? connectedVmService) async { } } class FakeApplicationPackageFactory implements ApplicationPackageFactory { diff --git a/packages/flutter_tools/test/commands.shard/hermetic/generate_localizations_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/generate_localizations_test.dart index 654c697b0a3..b911f8a1593 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/generate_localizations_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/generate_localizations_test.dart @@ -377,7 +377,7 @@ untranslated-messages-file: lib/l10n/untranslated.json }); // Regression test for https://github.com/flutter/flutter/issues/120530. - testWithoutContext('dart format is run when generateLocalizations is called through build target', () async { + testUsingContext('dart format is run when generateLocalizations is called through build target', () async { final File arbFile = fileSystem.file(fileSystem.path.join('lib', 'l10n', 'app_en.arb')) ..createSync(recursive: true); arbFile.writeAsStringSync(''' @@ -467,7 +467,7 @@ format: true pubspecFile.writeAsStringSync(''' name: test environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: @@ -506,7 +506,7 @@ format: true pubspecFile.writeAsStringSync(''' name: test environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/packages/flutter_tools/test/commands.shard/hermetic/proxied_devices_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/proxied_devices_test.dart index bbf6da01b84..738144f2b2e 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/proxied_devices_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/proxied_devices_test.dart @@ -71,7 +71,6 @@ void main() { daemon = Daemon( serverDaemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); fakeDevice = FakeAndroidDevice(); final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery(); @@ -93,7 +92,6 @@ void main() { daemon = Daemon( serverDaemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); fakeDevice = FakeAndroidDevice(); final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery(); @@ -116,7 +114,6 @@ void main() { daemon = Daemon( serverDaemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); fakeDevice = FakeAndroidDevice(); final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery(); @@ -147,7 +144,6 @@ void main() { daemon = Daemon( serverDaemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); fakeDevice = FakeAndroidDevice(); final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery(); @@ -201,7 +197,6 @@ void main() { daemon = Daemon( serverDaemonConnection, notifyingLogger: notifyingLogger, - useImplicitPubspecResolution: true, ); fakeDevice = FakeAndroidDevice(); final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery(); @@ -359,10 +354,7 @@ class FakeDeviceLogReader implements DeviceLogReader { bool disposeCalled = false; @override - int? appPid; - - @override - FlutterVmService? connectedVMService; + Future provideVmService(FlutterVmService? connectedVmService) async { } @override void dispose() { diff --git a/packages/flutter_tools/test/commands.shard/hermetic/run_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/run_test.dart index b9b88871fc2..8d474b943fd 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/run_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/run_test.dart @@ -27,9 +27,7 @@ import 'package:flutter_tools/src/macos/macos_ipad_device.dart'; import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/reporting/reporting.dart'; import 'package:flutter_tools/src/resident_runner.dart'; -import 'package:flutter_tools/src/run_hot.dart'; import 'package:flutter_tools/src/runner/flutter_command.dart'; -import 'package:flutter_tools/src/vmservice.dart'; import 'package:flutter_tools/src/web/compile.dart'; import 'package:test/fake.dart'; import 'package:unified_analytics/unified_analytics.dart' as analytics; @@ -1014,7 +1012,7 @@ void main() { () => createTestCommandRunner(command).run([ 'run', '--no-pub', - '--web-renderer=skwasm', + ...WebRendererMode.skwasm.toCliDartDefines, ]), throwsToolExit(message: 'Skwasm renderer requires --wasm')); }, overrides: { FileSystem: () => fileSystem, @@ -1032,7 +1030,7 @@ void main() { await createTestCommandRunner(RunCommand()).run([ 'run', '--no-pub', - '--web-renderer=${webRenderer.name}', + ...webRenderer.toCliDartDefines, ]); } on ToolExit catch (error) { expect(error, isA()); @@ -1129,7 +1127,7 @@ void main() { final FakeResidentRunner residentRunner = FakeResidentRunner(); residentRunner.rpcError = RPCError( 'flutter._listViews', - RPCErrorCodes.kServiceDisappeared, + RPCErrorKind.kServiceDisappeared.code, '', ); final TestRunCommandWithFakeResidentRunner command = TestRunCommandWithFakeResidentRunner(); @@ -1142,7 +1140,7 @@ void main() { residentRunner.rpcError = RPCError( 'flutter._listViews', - RPCErrorCodes.kServerError, + RPCErrorKind.kServerError.code, 'Service connection disposed.', ); @@ -1158,7 +1156,7 @@ void main() { testUsingContext('Flutter run does not catch other RPC errors', () async { final FakeResidentRunner residentRunner = FakeResidentRunner(); - residentRunner.rpcError = RPCError('flutter._listViews', RPCErrorCodes.kInvalidParams, ''); + residentRunner.rpcError = RPCError('flutter._listViews', RPCErrorKind.kInvalidParams.code, ''); final TestRunCommandWithFakeResidentRunner command = TestRunCommandWithFakeResidentRunner(); command.fakeResidentRunner = residentRunner; @@ -1584,14 +1582,14 @@ class DaemonCapturingRunCommand extends RunCommand { @override Daemon createMachineDaemon() { daemon = super.createMachineDaemon(); - appDomain = daemon.appDomain = CapturingAppDomain(daemon, useImplicitPubspecResolution: true); + appDomain = daemon.appDomain = CapturingAppDomain(daemon); daemon.registerDomain(appDomain); return daemon; } } class CapturingAppDomain extends AppDomain { - CapturingAppDomain(super.daemon, {required super.useImplicitPubspecResolution}); + CapturingAppDomain(super.daemon); String? userIdentifier; bool? enableDevTools; @@ -1612,7 +1610,6 @@ class CapturingAppDomain extends AppDomain { String? isolateFilter, bool machine = true, String? userIdentifier, - required HotRunnerNativeAssetsBuilder? nativeAssetsBuilder, }) async { this.userIdentifier = userIdentifier; enableDevTools = options.enableDevTools; diff --git a/packages/flutter_tools/test/commands.shard/hermetic/test_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/test_test.dart index ed8b362fb34..3e33452153b 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/test_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/test_test.dart @@ -1395,11 +1395,11 @@ dev_dependencies: final TestCommand testCommand = TestCommand(testRunner: testRunner); final CommandRunner commandRunner = createTestCommandRunner(testCommand); - await commandRunner.run(const [ + await commandRunner.run([ 'test', '--no-pub', '--platform=chrome', - '--web-renderer=canvaskit', + ...WebRendererMode.canvaskit.toCliDartDefines, ]); expect(testRunner.lastDebuggingOptionsValue.webRenderer, WebRendererMode.canvaskit); }, overrides: { @@ -1440,7 +1440,7 @@ dev_dependencies: 'web', '--no-pub', '--platform=chrome', - '--web-renderer=${webRenderer.name}', + ...webRenderer.toCliDartDefines, ]); } on ToolExit catch (error) { expect(error, isA()); @@ -1459,7 +1459,6 @@ dev_dependencies: .where((WebRendererMode mode) => mode.isDeprecated) .forEach(testWebRendererDeprecationMessage); - testUsingContext('Can test in a pub workspace', () async { final String root = fs.path.rootPrefix(fs.currentDirectory.absolute.path); diff --git a/packages/flutter_tools/test/commands.shard/hermetic/update_packages_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/update_packages_test.dart index 9f19c14b452..0ac9d597bd9 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/update_packages_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/update_packages_test.dart @@ -23,7 +23,7 @@ description: A framework for writing Flutter applications homepage: http://flutter.dev environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: # To update these, use "flutter update-packages --force-upgrade". diff --git a/packages/flutter_tools/test/commands.shard/hermetic/widget_preview_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/widget_preview_test.dart new file mode 100644 index 00000000000..5f5c9d133c0 --- /dev/null +++ b/packages/flutter_tools/test/commands.shard/hermetic/widget_preview_test.dart @@ -0,0 +1,236 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:file/memory.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/logger.dart'; +import 'package:flutter_tools/src/commands/widget_preview.dart'; +import 'package:flutter_tools/src/convert.dart'; +import 'package:flutter_tools/src/flutter_manifest.dart'; +import 'package:flutter_tools/src/project.dart'; +import 'package:test/test.dart'; +import 'package:test_api/fake.dart'; + +import '../../src/common.dart'; +import '../../src/context.dart'; + +void main() { + group('WidgetPreviewStartCommand', () { + late MemoryFileSystem fileSystem; + late ProcessManager processManager; + late WidgetPreviewStartCommand command; + late FlutterProject rootProject; + + setUp(() { + fileSystem = MemoryFileSystem.test(); + processManager = FakeProcessManager.any(); + command = WidgetPreviewStartCommand(); + rootProject = FakeFlutterProject( + projectRoot: 'some_project', + fileSystem: fileSystem, + logger: BufferLogger.test(), + ); + }); + + testUsingContext( + 'can create a pubspec.yaml for the preview scaffold including root project assets', + () { + final FlutterManifest root = rootProject.manifest; + final FlutterManifest updated = command.buildPubspec( + rootManifest: rootProject.manifest, + widgetPreviewManifest: + rootProject.widgetPreviewScaffoldProject.manifest, + ); + + final List rootAssets = root.assets; + final List updatedAssets = updated.assets; + expect(updatedAssets.length, rootAssets.length); + for (int i = 0; i < rootAssets.length; ++i) { + final AssetsEntry rootEntry = rootAssets[i]; + final AssetsEntry updatedEntry = updatedAssets[i]; + expect( + updatedEntry, + WidgetPreviewStartCommand.transformAssetsEntry(rootEntry), + ); + } + + expect(updated.fonts.length, root.fonts.length); + for (int i = 0; i < root.fonts.length; ++i) { + final Font rootFont = root.fonts[i]; + final Font updatedFont = updated.fonts[i]; + expect(updatedFont.familyName, rootFont.familyName); + expect(updatedFont.fontAssets.length, rootFont.fontAssets.length); + for (int j = 0; j < rootFont.fontAssets.length; ++j) { + final FontAsset rootFontAsset = rootFont.fontAssets[j]; + final FontAsset updatedFontAsset = updatedFont.fontAssets[j]; + expect( + updatedFontAsset.descriptor, + WidgetPreviewStartCommand.transformFontAsset(rootFontAsset) + .descriptor, + ); + } + } + + expect( + updated.shaders, + root.shaders.map(WidgetPreviewStartCommand.transformAssetUri), + ); + expect( + updated.models, + root.models.map(WidgetPreviewStartCommand.transformAssetUri), + ); + + expect( + updated.deferredComponents?.length, + root.deferredComponents?.length, + ); + if (root.deferredComponents != null) { + for (int i = 0; i < root.deferredComponents!.length; ++i) { + expect( + updated.deferredComponents![i].toString(), + WidgetPreviewStartCommand.transformDeferredComponent( + root.deferredComponents![i], + ).toString(), + ); + } + } + }, + overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }, + ); + + testUsingContext( + 'can add flutter_gen to package_config.json if generate is set in the parent project', + () async { + command.maybeAddFlutterGenToPackageConfig(rootProject: rootProject); + final Map packageConfig = jsonDecode( + rootProject.widgetPreviewScaffoldProject.packageConfig + .readAsStringSync(), + ) as Map; + expect(packageConfig.containsKey('packages'), true); + final List> packages = + (packageConfig['packages']! as List) + .cast>(); + expect(packages.length, 2); + expect( + packages.last, + WidgetPreviewStartCommand.flutterGenPackageConfigEntry, + ); + }, + overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }, + ); + }); +} + +class FakeFlutterProject extends Fake implements FlutterProject { + FakeFlutterProject({ + required this.projectRoot, + required this.fileSystem, + required this.logger, + }); + + static const String complexPubspec = ''' +name: test +dependencies: + flutter: + sdk: flutter +flutter: + uses-material-design: true + generate: true + assets: + - path: foo + flavors: + - flavor + transformers: + - package: package:foo + args: + - arg + - path: package/foo + fonts: + - family: fontFamily + fonts: + - weight: 100 + style: normal + asset: assetUri + - weight: 200 + style: italic + asset: package/assetUri + shaders: + - shaderUri + models: + - modelUri + deferred-components: + - name: deferredComponent + libraries: + - deferredComponentLibrary + assets: + - path: deferredComponentUri + flavors: + - deferredComponentFlavor + transformers: + - package: package:deferredComponent + args: + - deferredComponentArg + - path: package/deferredComponentUri'''; + + static const String basicPackageConfig = ''' +{ + "configVersion": 2, + "packages": [ + { + "name": "test", + "rootUri": "fileSystem.currentDirectory.path", + "packageUri": "lib/" + } + ] +} +'''; + + final String projectRoot; + final FileSystem fileSystem; + final Logger logger; + + @override + late final FlutterManifest manifest = FlutterManifest.createFromPath( + pubspecFile.path, + fileSystem: fileSystem, + logger: logger, + )!; + + @override + late FlutterProject widgetPreviewScaffoldProject = FakeFlutterProject( + projectRoot: fileSystem.path.join( + projectRoot, + '.dart_tool', + 'widget_preview_scaffold', + ), + fileSystem: fileSystem, + logger: logger, + ); + + @override + late final File pubspecFile = () { + final File file = fileSystem + .directory(projectRoot) + .childFile('pubspec.yaml') + ..createSync(recursive: true); + file.writeAsStringSync(complexPubspec); + return file; + }(); + + @override + late final File packageConfig = () { + final File file = fileSystem + .directory(fileSystem.path.join(projectRoot, '.dart_tool')) + .childFile('package_config.json') + ..createSync(recursive: true); + file.writeAsStringSync(basicPackageConfig); + return file; + }(); +} diff --git a/packages/flutter_tools/test/commands.shard/permeable/build_aar_test.dart b/packages/flutter_tools/test/commands.shard/permeable/build_aar_test.dart index 468f3d5d0b6..7291d6ae07a 100644 --- a/packages/flutter_tools/test/commands.shard/permeable/build_aar_test.dart +++ b/packages/flutter_tools/test/commands.shard/permeable/build_aar_test.dart @@ -300,7 +300,7 @@ void main() { group('Impeller AndroidManifest.xml setting', () { // Adds a key-value `` pair to the `` tag in the - // cooresponding `AndroidManifest.xml` file, right before the closing + // corresponding `AndroidManifest.xml` file, right before the closing // `` tag. void writeManifestMetadata({ required String projectPath, diff --git a/packages/flutter_tools/test/commands.shard/permeable/build_appbundle_test.dart b/packages/flutter_tools/test/commands.shard/permeable/build_appbundle_test.dart index 5cc71c77d3e..d843983a581 100644 --- a/packages/flutter_tools/test/commands.shard/permeable/build_appbundle_test.dart +++ b/packages/flutter_tools/test/commands.shard/permeable/build_appbundle_test.dart @@ -7,6 +7,7 @@ import 'package:file/memory.dart'; import 'package:flutter_tools/src/android/android_builder.dart'; import 'package:flutter_tools/src/android/android_sdk.dart'; import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/build_appbundle.dart'; @@ -27,6 +28,7 @@ void main() { group('analytics', () { late Directory tempDir; late FakeAnalytics fakeAnalytics; + late FakeProcessInfo processInfo; setUp(() { tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_packages_test.'); @@ -34,6 +36,7 @@ void main() { fs: MemoryFileSystem.test(), fakeFlutterVersion: FakeFlutterVersion(), ); + processInfo = FakeProcessInfo(); }); tearDown(() { @@ -135,7 +138,7 @@ void main() { commandPath: 'create', result: 'success', commandHasTerminal: false, - maxRss: globals.processInfo.maxRss, + maxRss: processInfo.maxRss, ), ), ); @@ -143,6 +146,50 @@ void main() { overrides: { AndroidBuilder: () => FakeAndroidBuilder(), Analytics: () => fakeAnalytics, + ProcessInfo: () => processInfo, + }); + + testUsingContext('use of the deferred components feature sends a build info event indicating so', () async { + final String projectPath = await createProject( + tempDir, + arguments: [ + '--empty', + '--no-pub', + '--template=app', + ], + ); + + // Add deferred manifest. + final File pubspec = globals.localFileSystem + .directory(projectPath) + .childFile('pubspec.yaml'); + final String modifiedContents = pubspec + .readAsStringSync() + .replaceAll('flutter:', 'flutter:\n deferred-components:'); + pubspec.writeAsStringSync(modifiedContents); + printOnFailure(pubspec.readAsStringSync()); + + final Directory oldCwd = globals.localFileSystem.currentDirectory; + try { + globals.localFileSystem.currentDirectory = globals.localFileSystem.directory(projectPath); + await runBuildAppBundleCommand(projectPath); + } finally { + globals.localFileSystem.currentDirectory = oldCwd; + } + + expect( + fakeAnalytics.sentEvents, + contains( + Event.flutterBuildInfo( + label: 'build-appbundle-deferred-components', + buildType: 'android', + ), + ), + ); + }, overrides: { + AndroidBuilder: () => FakeAndroidBuilder(), + Analytics: () => fakeAnalytics, + ProcessInfo: () => processInfo, }); }); @@ -291,3 +338,8 @@ class FakeAndroidSdk extends Fake implements AndroidSdk { @override final Directory directory; } + +class FakeProcessInfo extends Fake implements ProcessInfo { + @override + int maxRss = 123456789; +} diff --git a/packages/flutter_tools/test/commands.shard/permeable/build_bundle_test.dart b/packages/flutter_tools/test/commands.shard/permeable/build_bundle_test.dart index 143fd71414f..5a31b0b8a25 100644 --- a/packages/flutter_tools/test/commands.shard/permeable/build_bundle_test.dart +++ b/packages/flutter_tools/test/commands.shard/permeable/build_bundle_test.dart @@ -70,9 +70,8 @@ void main() { final String projectPath = await createProject(tempDir, arguments: ['--no-pub', '--template=module']); - final BuildBundleCommand command = await runCommandIn(projectPath); + await runCommandIn(projectPath); - expect((await command.usageValues).commandBuildBundleIsModule, true); expect( fakeAnalytics.sentEvents, contains( @@ -544,6 +543,5 @@ class FakeBundleBuilder extends Fake implements BundleBuilder { String? assetDirPath, bool buildNativeAssets = true, @visibleForTesting BuildSystem? buildSystem, - required bool useImplicitPubspecResolution, }) async {} } diff --git a/packages/flutter_tools/test/commands.shard/permeable/create_test.dart b/packages/flutter_tools/test/commands.shard/permeable/create_test.dart index a59303fadc9..98f1aadbd87 100644 --- a/packages/flutter_tools/test/commands.shard/permeable/create_test.dart +++ b/packages/flutter_tools/test/commands.shard/permeable/create_test.dart @@ -29,7 +29,6 @@ import 'package:flutter_tools/src/flutter_project_metadata.dart' show FlutterPro import 'package:flutter_tools/src/globals.dart' as globals; import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/version.dart'; -import 'package:process/process.dart'; import 'package:pub_semver/pub_semver.dart'; import 'package:pubspec_parse/pubspec_parse.dart'; import 'package:unified_analytics/unified_analytics.dart'; @@ -42,6 +41,7 @@ import '../../src/fake_http_client.dart'; import '../../src/fakes.dart'; import '../../src/pubspec_schema.dart'; import '../../src/test_flutter_command_runner.dart'; +import 'utils/project_testing_utils.dart'; const String _kNoPlatformsMessage = "You've created a plugin project that doesn't yet support any platforms.\n"; const String frameworkRevision = '12345678'; @@ -84,7 +84,7 @@ void main() { setUpAll(() async { Cache.disableLocking(); - await _ensureFlutterToolsSnapshot(); + await ensureFlutterToolsSnapshot(); }); setUp(() { @@ -109,7 +109,7 @@ void main() { }); tearDownAll(() async { - await _restoreFlutterToolsSnapshot(); + await restoreFlutterToolsSnapshot(); }); test('createAndroidIdentifier emits a valid identifier', () { @@ -2472,7 +2472,7 @@ void main() { await runner.run(['create', '--no-pub', '--template=plugin', projectDir.path]); await _getPackages(projectDir); - await _analyzeProject(projectDir.path); + await analyzeProject(projectDir.path); await _runFlutterTest(projectDir); }, overrides: { FeatureFlags: () => TestFeatureFlags(), @@ -2489,7 +2489,7 @@ void main() { final Directory exampleDir = projectDir.childDirectory('example'); await _getPackages(exampleDir); - await _analyzeProject(exampleDir.path); + await analyzeProject(exampleDir.path); await _runFlutterTest(exampleDir); }); @@ -2554,7 +2554,7 @@ void main() { expect(logger.errorText, isNot(contains(_kNoPlatformsMessage))); await _getPackages(projectDir); - await _analyzeProject(projectDir.path); + await analyzeProject(projectDir.path); await _runFlutterTest(projectDir); }, overrides: { FeatureFlags: () => TestFeatureFlags(isWebEnabled: true), @@ -3603,7 +3603,7 @@ void main() { '$relativePath:31:26: use_full_hex_values_for_flutter_colors', ]; expect(expectedFailures.length, '// LINT:'.allMatches(toAnalyze.readAsStringSync()).length); - await _analyzeProject( + await analyzeProject( projectDir.path, expectedFailures: expectedFailures, ); @@ -4116,122 +4116,7 @@ Future _createAndAnalyzeProject( unexpectedPaths: unexpectedPaths, expectedGitignoreLines: expectedGitignoreLines, ); - await _analyzeProject(dir.path); -} - -Future _ensureFlutterToolsSnapshot() async { - final String flutterToolsPath = globals.fs.path.absolute(globals.fs.path.join( - 'bin', - 'flutter_tools.dart', - )); - final String flutterToolsSnapshotPath = globals.fs.path.absolute(globals.fs.path.join( - '..', - '..', - 'bin', - 'cache', - 'flutter_tools.snapshot', - )); - final String packageConfig = globals.fs.path.absolute(globals.fs.path.join( - '.dart_tool', - 'package_config.json' - )); - - final File snapshotFile = globals.fs.file(flutterToolsSnapshotPath); - if (snapshotFile.existsSync()) { - snapshotFile.renameSync('$flutterToolsSnapshotPath.bak'); - } - - final List snapshotArgs = [ - '--snapshot=$flutterToolsSnapshotPath', - '--packages=$packageConfig', - flutterToolsPath, - ]; - final ProcessResult snapshotResult = await Process.run( - '../../bin/cache/dart-sdk/bin/dart', - snapshotArgs, - ); - printOnFailure('Results of generating snapshot:'); - printOnFailure(snapshotResult.stdout.toString()); - printOnFailure(snapshotResult.stderr.toString()); - expect(snapshotResult.exitCode, 0); -} - -Future _restoreFlutterToolsSnapshot() async { - final String flutterToolsSnapshotPath = globals.fs.path.absolute(globals.fs.path.join( - '..', - '..', - 'bin', - 'cache', - 'flutter_tools.snapshot', - )); - - final File snapshotBackup = globals.fs.file('$flutterToolsSnapshotPath.bak'); - if (!snapshotBackup.existsSync()) { - // No backup to restore. - return; - } - - snapshotBackup.renameSync(flutterToolsSnapshotPath); -} - -Future _analyzeProject(String workingDir, { List expectedFailures = const [] }) async { - final String flutterToolsSnapshotPath = globals.fs.path.absolute(globals.fs.path.join( - '..', - '..', - 'bin', - 'cache', - 'flutter_tools.snapshot', - )); - - final List args = [ - flutterToolsSnapshotPath, - 'analyze', - ]; - - final ProcessResult exec = await Process.run( - globals.artifacts!.getArtifactPath(Artifact.engineDartBinary), - args, - workingDirectory: workingDir, - ); - if (expectedFailures.isEmpty) { - printOnFailure('Results of running analyzer:'); - printOnFailure(exec.stdout.toString()); - printOnFailure(exec.stderr.toString()); - expect(exec.exitCode, 0); - return; - } - expect(exec.exitCode, isNot(0)); - String lineParser(String line) { - try { - final String analyzerSeparator = globals.platform.isWindows ? ' - ' : ' • '; - final List lineComponents = line.trim().split(analyzerSeparator); - final String lintName = lineComponents.removeLast(); - final String location = lineComponents.removeLast(); - return '$location: $lintName'; - } on RangeError catch (err) { - throw RangeError('Received "$err" while trying to parse: "$line".'); - } - } - final String stdout = exec.stdout.toString(); - final List errors = []; - try { - bool analyzeLineFound = false; - const LineSplitter().convert(stdout).forEach((String line) { - // Conditional to filter out any stdout from `pub get` - if (!analyzeLineFound && line.startsWith('Analyzing')) { - analyzeLineFound = true; - return; - } - - if (analyzeLineFound && line.trim().isNotEmpty) { - errors.add(lineParser(line.trim())); - } - }); - } on Exception catch (err) { - fail('$err\n\nComplete STDOUT was:\n\n$stdout'); - } - expect(errors, unorderedEquals(expectedFailures), - reason: 'Failed with stdout:\n\n$stdout'); + await analyzeProject(dir.path); } Future _getPackages(Directory workingDir) async { @@ -4285,35 +4170,7 @@ Future _runFlutterTest(Directory workingDir, { String? target }) async { expect(exec.exitCode, 0); } -/// A ProcessManager that invokes a real process manager, but keeps -/// track of all commands sent to it. -class LoggingProcessManager extends LocalProcessManager { - List> commands = >[]; - @override - Future start( - List command, { - String? workingDirectory, - Map? environment, - bool includeParentEnvironment = true, - bool runInShell = false, - ProcessStartMode mode = ProcessStartMode.normal, - }) { - commands.add(command.map((Object arg) => arg.toString()).toList()); - return super.start( - command, - workingDirectory: workingDirectory, - environment: environment, - includeParentEnvironment: includeParentEnvironment, - runInShell: runInShell, - mode: mode, - ); - } - - void clear() { - commands.clear(); - } -} String _getStringValueFromPlist({required File plistFile, String? key}) { final List plist = plistFile.readAsLinesSync().map((String line) => line.trim()).toList(); diff --git a/packages/flutter_tools/test/commands.shard/permeable/packages_test.dart b/packages/flutter_tools/test/commands.shard/permeable/packages_test.dart index 31101526e14..bbba64cf0a1 100644 --- a/packages/flutter_tools/test/commands.shard/permeable/packages_test.dart +++ b/packages/flutter_tools/test/commands.shard/permeable/packages_test.dart @@ -15,6 +15,7 @@ import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/packages.dart'; import 'package:flutter_tools/src/dart/pub.dart'; +import 'package:flutter_tools/src/features.dart'; import 'package:flutter_tools/src/globals.dart' as globals; import 'package:unified_analytics/unified_analytics.dart'; import 'package:yaml/yaml.dart'; @@ -333,7 +334,7 @@ flutter: tempDir.childFile('pubspec.yaml').writeAsStringSync(''' name: workspace environment: - sdk: ^3.5.0-0 + sdk: ^3.7.0-0 workspace: - flutter_project '''); @@ -636,7 +637,7 @@ workspace: ), }); - testUsingContext('get --no-implicit-pubspec-resolution omits ".flutter-plugins"', () async { + testUsingContext('get explicit-packages-resolution omits ".flutter-plugins"', () async { final String projectPath = await createProject( tempDir, arguments: ['--template=plugin', '--no-pub', '--platforms=ios,android'], @@ -646,12 +647,15 @@ workspace: removeGeneratedFiles(exampleProjectPath); // Running flutter packages get also resolves the dependencies in the example/ project. - await runCommandIn(projectPath, 'get', globalArgs: ['--no-implicit-pubspec-resolution']); + await runCommandIn(projectPath, 'get'); expectDependenciesResolved(projectPath); expectDependenciesResolved(exampleProjectPath); expectPluginInjected(exampleProjectPath, includeLegacyPluginsList: false); }, overrides: { + FeatureFlags: () => TestFeatureFlags( + isExplicitPackageDependenciesEnabled: true, + ), Stdio: () => mockStdio, Pub: () => Pub.test( fileSystem: globals.fs, diff --git a/packages/flutter_tools/test/commands.shard/permeable/utils/project_testing_utils.dart b/packages/flutter_tools/test/commands.shard/permeable/utils/project_testing_utils.dart new file mode 100644 index 00000000000..d95e44c824c --- /dev/null +++ b/packages/flutter_tools/test/commands.shard/permeable/utils/project_testing_utils.dart @@ -0,0 +1,159 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:convert'; + +import 'package:flutter_tools/src/artifacts.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; +import 'package:flutter_tools/src/globals.dart' as globals; +import 'package:process/process.dart'; + +import '../../../src/test_flutter_command_runner.dart'; + +/// A ProcessManager that invokes a real process manager, but keeps +/// track of all commands sent to it. +class LoggingProcessManager extends LocalProcessManager { + List> commands = >[]; + + @override + Future start( + List command, { + String? workingDirectory, + Map? environment, + bool includeParentEnvironment = true, + bool runInShell = false, + ProcessStartMode mode = ProcessStartMode.normal, + }) { + commands.add(command.map((Object arg) => arg.toString()).toList()); + return super.start( + command, + workingDirectory: workingDirectory, + environment: environment, + includeParentEnvironment: includeParentEnvironment, + runInShell: runInShell, + mode: mode, + ); + } + + void clear() { + commands.clear(); + } +} + +Future analyzeProject(String workingDir, { List expectedFailures = const [] }) async { + final String flutterToolsSnapshotPath = globals.fs.path.absolute(globals.fs.path.join( + '..', + '..', + 'bin', + 'cache', + 'flutter_tools.snapshot', + )); + + final List args = [ + flutterToolsSnapshotPath, + 'analyze', + ]; + + final ProcessResult exec = await Process.run( + globals.artifacts!.getArtifactPath(Artifact.engineDartBinary), + args, + workingDirectory: workingDir, + ); + if (expectedFailures.isEmpty) { + printOnFailure('Results of running analyzer:'); + printOnFailure(exec.stdout.toString()); + printOnFailure(exec.stderr.toString()); + expect(exec.exitCode, 0); + return; + } + expect(exec.exitCode, isNot(0)); + String lineParser(String line) { + try { + final String analyzerSeparator = globals.platform.isWindows ? ' - ' : ' • '; + final List lineComponents = line.trim().split(analyzerSeparator); + final String lintName = lineComponents.removeLast(); + final String location = lineComponents.removeLast(); + return '$location: $lintName'; + } on RangeError catch (err) { + throw RangeError('Received "$err" while trying to parse: "$line".'); + } + } + final String stdout = exec.stdout.toString(); + final List errors = []; + try { + bool analyzeLineFound = false; + const LineSplitter().convert(stdout).forEach((String line) { + // Conditional to filter out any stdout from `pub get` + if (!analyzeLineFound && line.startsWith('Analyzing')) { + analyzeLineFound = true; + return; + } + + if (analyzeLineFound && line.trim().isNotEmpty) { + errors.add(lineParser(line.trim())); + } + }); + } on Exception catch (err) { + fail('$err\n\nComplete STDOUT was:\n\n$stdout'); + } + expect(errors, unorderedEquals(expectedFailures), + reason: 'Failed with stdout:\n\n$stdout'); +} + + +Future ensureFlutterToolsSnapshot() async { + final String flutterToolsPath = globals.fs.path.absolute(globals.fs.path.join( + 'bin', + 'flutter_tools.dart', + )); + final String flutterToolsSnapshotPath = globals.fs.path.absolute(globals.fs.path.join( + '..', + '..', + 'bin', + 'cache', + 'flutter_tools.snapshot', + )); + final String packageConfig = globals.fs.path.absolute(globals.fs.path.join( + '.dart_tool', + 'package_config.json' + )); + + final File snapshotFile = globals.fs.file(flutterToolsSnapshotPath); + if (snapshotFile.existsSync()) { + snapshotFile.renameSync('$flutterToolsSnapshotPath.bak'); + } + + final List snapshotArgs = [ + '--snapshot=$flutterToolsSnapshotPath', + '--packages=$packageConfig', + flutterToolsPath, + ]; + final ProcessResult snapshotResult = await Process.run( + '../../bin/cache/dart-sdk/bin/dart', + snapshotArgs, + ); + printOnFailure('Results of generating snapshot:'); + printOnFailure(snapshotResult.stdout.toString()); + printOnFailure(snapshotResult.stderr.toString()); + expect(snapshotResult.exitCode, 0); +} + +Future restoreFlutterToolsSnapshot() async { + final String flutterToolsSnapshotPath = globals.fs.path.absolute(globals.fs.path.join( + '..', + '..', + 'bin', + 'cache', + 'flutter_tools.snapshot', + )); + + final File snapshotBackup = globals.fs.file('$flutterToolsSnapshotPath.bak'); + if (!snapshotBackup.existsSync()) { + // No backup to restore. + return; + } + + snapshotBackup.renameSync(flutterToolsSnapshotPath); +} diff --git a/packages/flutter_tools/test/commands.shard/permeable/widget_preview_test.dart b/packages/flutter_tools/test/commands.shard/permeable/widget_preview_test.dart new file mode 100644 index 00000000000..da46ae707e8 --- /dev/null +++ b/packages/flutter_tools/test/commands.shard/permeable/widget_preview_test.dart @@ -0,0 +1,276 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:io' as io show IOOverrides; + +import 'package:args/command_runner.dart'; +import 'package:file_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/common.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/commands/widget_preview.dart'; +import 'package:flutter_tools/src/dart/pub.dart'; +import 'package:flutter_tools/src/globals.dart' as globals; + +import '../../src/common.dart'; +import '../../src/context.dart'; +import '../../src/fakes.dart'; +import '../../src/test_flutter_command_runner.dart'; +import 'utils/project_testing_utils.dart'; + +void main() { + late Directory tempDir; + late LoggingProcessManager loggingProcessManager; + late FakeStdio mockStdio; + + setUp(() { + loggingProcessManager = LoggingProcessManager(); + tempDir = globals.fs.systemTempDirectory + .createTempSync('flutter_tools_create_test.'); + mockStdio = FakeStdio(); + }); + + tearDown(() { + tryToDelete(tempDir); + }); + + Future createRootProject() async { + return createProject( + tempDir, + arguments: ['--pub'], + ); + } + + Future runWidgetPreviewCommand(List arguments) async { + final CommandRunner runner = createTestCommandRunner( + WidgetPreviewCommand(), + ); + await runner.run(['widget-preview', ...arguments]); + } + + Future startWidgetPreview({ + required String? rootProjectPath, + List? arguments, + }) async { + await runWidgetPreviewCommand( + [ + 'start', + ...?arguments, + if (rootProjectPath != null) rootProjectPath, + ], + ); + expect( + globals.fs + .directory(rootProjectPath ?? globals.fs.currentDirectory.path) + .childDirectory('.dart_tool') + .childDirectory('widget_preview_scaffold'), + exists, + ); + } + + Future cleanWidgetPreview({ + required String rootProjectPath, + }) async { + await runWidgetPreviewCommand(['clean', rootProjectPath]); + expect( + globals.fs + .directory(rootProjectPath) + .childDirectory('.dart_tool') + .childDirectory('widget_preview_scaffold'), + isNot(exists), + ); + } + + group('flutter widget-preview', () { + group('start exits if', () { + testUsingContext( + 'given an invalid directory', + () async { + try { + await runWidgetPreviewCommand( + [ + 'start', + 'foo', + ], + ); + fail( + 'Successfully executed with multiple project paths', + ); + } on ToolExit catch (e) { + expect( + e.message, + contains( + 'Could not find foo', + ), + ); + } + }, + ); + + testUsingContext( + 'more than one project directory is provided', + () async { + try { + await runWidgetPreviewCommand( + [ + 'start', + tempDir.path, + tempDir.path, + ], + ); + fail( + 'Successfully executed with multiple project paths', + ); + } on ToolExit catch (e) { + expect( + e.message, + contains( + 'Only one directory should be provided.', + ), + ); + } + }, + ); + + testUsingContext( + 'run outside of a Flutter project directory', + () async { + try { + await startWidgetPreview(rootProjectPath: tempDir.path); + fail( + 'Successfully executed outside of a Flutter project directory', + ); + } on ToolExit catch (e) { + expect( + e.message, + contains( + '${tempDir.path} is not a valid Flutter project.', + ), + ); + } + }, + ); + }); + + testUsingContext( + 'start creates .dart_tool/widget_preview_scaffold', + () async { + final String rootProjectPath = await createRootProject(); + await startWidgetPreview(rootProjectPath: rootProjectPath); + }, + overrides: { + Pub: () => Pub.test( + fileSystem: globals.fs, + logger: globals.logger, + processManager: globals.processManager, + usage: globals.flutterUsage, + botDetector: globals.botDetector, + platform: globals.platform, + stdio: mockStdio, + ), + }, + ); + + testUsingContext( + 'start creates .dart_tool/widget_preview_scaffold in the CWD', + () async { + final String rootProjectPath = await createRootProject(); + await io.IOOverrides.runZoned>( + () async { + // Try to execute using the CWD. + await startWidgetPreview(rootProjectPath: null); + }, + getCurrentDirectory: () => globals.fs.directory(rootProjectPath), + ); + }, + overrides: { + Pub: () => Pub.test( + fileSystem: globals.fs, + logger: globals.logger, + processManager: globals.processManager, + usage: globals.flutterUsage, + botDetector: globals.botDetector, + platform: globals.platform, + stdio: mockStdio, + ), + }, + ); + + testUsingContext( + 'clean deletes .dart_tool/widget_preview_scaffold', + () async { + final String rootProjectPath = await createRootProject(); + await startWidgetPreview(rootProjectPath: rootProjectPath); + await cleanWidgetPreview(rootProjectPath: rootProjectPath); + }, + overrides: { + Pub: () => Pub.test( + fileSystem: globals.fs, + logger: globals.logger, + processManager: globals.processManager, + usage: globals.flutterUsage, + botDetector: globals.botDetector, + platform: globals.platform, + stdio: mockStdio, + ), + }, + ); + + testUsingContext( + 'invokes pub in online and offline modes', + () async { + // Run pub online first in order to populate the pub cache. + final String rootProjectPath = await createRootProject(); + loggingProcessManager.clear(); + + final RegExp dartCommand = RegExp(r'dart-sdk[\\/]bin[\\/]dart'); + + await startWidgetPreview(rootProjectPath: rootProjectPath); + expect( + loggingProcessManager.commands, + contains( + predicate( + (List c) => + dartCommand.hasMatch(c[0]) && + c[1].contains('pub') && + !c.contains('--offline'), + ), + ), + ); + + await cleanWidgetPreview(rootProjectPath: rootProjectPath); + + // Run pub offline. + loggingProcessManager.clear(); + await startWidgetPreview( + rootProjectPath: rootProjectPath, + arguments: ['--pub', '--offline'], + ); + + expect( + loggingProcessManager.commands, + contains( + predicate( + (List c) => + dartCommand.hasMatch(c[0]) && + c[1].contains('pub') && + c.contains('--offline'), + ), + ), + ); + }, + overrides: { + ProcessManager: () => loggingProcessManager, + Pub: () => Pub.test( + fileSystem: globals.fs, + logger: globals.logger, + processManager: globals.processManager, + usage: globals.flutterUsage, + botDetector: globals.botDetector, + platform: globals.platform, + stdio: mockStdio, + ), + }, + ); + }); +} diff --git a/packages/flutter_tools/test/general.shard/android/adb_log_reader_test.dart b/packages/flutter_tools/test/general.shard/android/adb_log_reader_test.dart index 543aff1c7ca..2f6d264d36f 100644 --- a/packages/flutter_tools/test/general.shard/android/adb_log_reader_test.dart +++ b/packages/flutter_tools/test/general.shard/android/adb_log_reader_test.dart @@ -5,7 +5,10 @@ import 'dart:async'; import 'package:flutter_tools/src/android/android_device.dart'; +import 'package:flutter_tools/src/base/logger.dart'; +import 'package:flutter_tools/src/vmservice.dart'; import 'package:test/fake.dart'; +import 'package:vm_service/vm_service.dart'; import '../../src/common.dart'; import '../../src/fake_process_manager.dart'; @@ -18,6 +21,24 @@ const String kLastLogcatTimestamp = '11-27 15:39:04.506'; /// line as the first input to disable this behavior. const String kDummyLine = 'Contents are not important\n'; +class _FakeVm extends Fake implements VM { + _FakeVm(this._appPid); + + final int _appPid; + + @override + int? get pid => _appPid; +} + +class _FakeFlutterVmService extends Fake implements FlutterVmService { + _FakeFlutterVmService(this._appPid); + + final int _appPid; + + @override + Future getVmGuarded() async => _FakeVm(_appPid); +} + void main() { testWithoutContext('AdbLogReader ignores spam from SurfaceSyncer', () async { const int appPid = 1; @@ -44,7 +65,9 @@ void main() { final AdbLogReader logReader = await AdbLogReader.createLogReader( createFakeDevice(null), processManager, - )..appPid = appPid; + BufferLogger.test(), + ); + await logReader.provideVmService(_FakeFlutterVmService(appPid)); final Completer onDone = Completer.sync(); final List emittedLines = []; logReader.logLines.listen((String line) { @@ -76,6 +99,7 @@ void main() { await AdbLogReader.createLogReader( createFakeDevice(kLollipopVersionCode), processManager, + BufferLogger.test(), ); expect(processManager, hasNoRemainingExpectations); @@ -99,6 +123,7 @@ void main() { await AdbLogReader.createLogReader( createFakeDevice(kLollipopVersionCode - 1), processManager, + BufferLogger.test(), ); expect(processManager, hasNoRemainingExpectations); @@ -122,6 +147,7 @@ void main() { await AdbLogReader.createLogReader( createFakeDevice(null), processManager, + BufferLogger.test(), ); expect(processManager, hasNoRemainingExpectations); @@ -147,6 +173,7 @@ void main() { await AdbLogReader.createLogReader( createFakeDevice(null), processManager, + BufferLogger.test(), includePastLogs: true, ); @@ -173,6 +200,7 @@ void main() { final AdbLogReader logReader = await AdbLogReader.createLogReader( createFakeDevice(null), processManager, + BufferLogger.test(), ); final Completer onDone = Completer.sync(); logReader.logLines.listen((String _) { }, onDone: onDone.complete); @@ -207,6 +235,7 @@ void main() { final AdbLogReader logReader = await AdbLogReader.createLogReader( createFakeDevice(null), processManager, + BufferLogger.test() ); await expectLater(logReader.logLines, emitsInOrder([ 'E/AndroidRuntime(11787): FATAL EXCEPTION: main', diff --git a/packages/flutter_tools/test/general.shard/android/android_device_test.dart b/packages/flutter_tools/test/general.shard/android/android_device_test.dart index 99898c28c11..dcf49224e65 100644 --- a/packages/flutter_tools/test/general.shard/android/android_device_test.dart +++ b/packages/flutter_tools/test/general.shard/android/android_device_test.dart @@ -16,10 +16,14 @@ import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/device.dart'; +import 'package:flutter_tools/src/globals.dart' as globals; import 'package:flutter_tools/src/project.dart'; +import 'package:flutter_tools/src/vmservice.dart'; import 'package:test/fake.dart'; +import 'package:vm_service/vm_service.dart'; import '../../src/common.dart'; +import '../../src/context.dart'; import '../../src/fake_process_manager.dart'; void main() { @@ -470,6 +474,34 @@ Uptime: 441088659 Realtime: 521464097 expect(await device.stopApp(null), isFalse); }); + testUsingContext('AdbLogReader.provideVmService catches any RPCError due to VM service disconnection', () async { + final BufferLogger logger = globals.logger as BufferLogger; + final FlutterVmService vmService = FlutterVmService(_MyFakeVmService()); + final AdbLogReader logReader = AdbLogReader.test( + FakeProcess(), + 'foo', + logger, + ); + await logReader.provideVmService(vmService); + expect( + logger.traceText, + 'VmService.getVm call failed: null: (-32000) ' + 'Service connection disposed\n', + ); + expect( + logger.errorText, + 'An error occurred when setting up filtering for adb logs. ' + 'Unable to communicate with the VM service.\n', + ); + }, overrides: { + Logger: () => BufferLogger.test(), + }); +} + +class _MyFakeVmService extends Fake implements VmService { + @override Future getVM() async { + throw RPCError(null, RPCErrorKind.kServerError.code, 'Service connection disposed'); + } } AndroidDevice setUpAndroidDevice({ diff --git a/packages/flutter_tools/test/general.shard/android/android_gradle_builder_test.dart b/packages/flutter_tools/test/general.shard/android/android_gradle_builder_test.dart index 36f40a750ec..a80a0e336e2 100644 --- a/packages/flutter_tools/test/general.shard/android/android_gradle_builder_test.dart +++ b/packages/flutter_tools/test/general.shard/android/android_gradle_builder_test.dart @@ -811,6 +811,85 @@ void main() { AndroidStudio: () => FakeAndroidStudio(), }); + testUsingContext('prints deprecation warning when building for x86', () async { + // See https://github.com/flutter/flutter/issues/157543 for details. + final AndroidGradleBuilder builder = AndroidGradleBuilder( + java: FakeJava(), + logger: logger, + processManager: processManager, + fileSystem: fileSystem, + artifacts: Artifacts.test(), + analytics: fakeAnalytics, + gradleUtils: FakeGradleUtils(), + platform: FakePlatform(), + androidStudio: FakeAndroidStudio(), + ); + processManager.addCommand(const FakeCommand( + command: [ + 'gradlew', + '-q', + '-Ptarget-platform=android-x86', + '-Ptarget=lib/main.dart', + '-Pbase-application-name=android.app.Application', + '-Pdart-obfuscation=false', + '-Ptrack-widget-creation=false', + '-Ptree-shake-icons=false', + 'assembleRelease', + ], + )); + fileSystem.directory('android') + .childFile('build.gradle') + .createSync(recursive: true); + + fileSystem.directory('android') + .childFile('gradle.properties') + .createSync(recursive: true); + + fileSystem.directory('android') + .childDirectory('app') + .childFile('build.gradle') + ..createSync(recursive: true) + ..writeAsStringSync('apply from: irrelevant/flutter.gradle'); + + fileSystem.directory('build') + .childDirectory('app') + .childDirectory('outputs') + .childDirectory('flutter-apk') + .childFile('app-release.apk') + .createSync(recursive: true); + + final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); + project.android.appManifestFile + ..createSync(recursive: true) + ..writeAsStringSync(minimalV2EmbeddingManifest); + + await builder.buildGradleApp( + project: project, + androidBuildInfo: const AndroidBuildInfo( + BuildInfo( + BuildMode.release, + null, + treeShakeIcons: false, + packageConfigPath: '.dart_tool/package_config.json', + ), + targetArchs: [AndroidArch.x86], + ), + target: 'lib/main.dart', + isBuildingBundle: false, + configOnly: false, + localGradleErrors: const [], + ); + + expect( + logger.statusText, + contains('Built build/app/outputs/flutter-apk/app-release.apk (0.0MB)'), + ); + expect(logger.warningText, contains(androidX86DeprecationWarning)); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + AndroidStudio: () => FakeAndroidStudio(), + }); + testUsingContext('Uses namespace attribute if manifest lacks a package attribute', () async { final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); final AndroidSdk sdk = FakeAndroidSdk(); diff --git a/packages/flutter_tools/test/general.shard/android/android_workflow_test.dart b/packages/flutter_tools/test/general.shard/android/android_workflow_test.dart index 385efafd589..74f0772c913 100644 --- a/packages/flutter_tools/test/general.shard/android/android_workflow_test.dart +++ b/packages/flutter_tools/test/general.shard/android/android_workflow_test.dart @@ -637,6 +637,146 @@ Android sdkmanager tool was found, but failed to run expect(processManager, hasNoRemainingExpectations); expect(stdio.stderr.getAndClear(), contains('UnsupportedClassVersionError')); }); + + testWithoutContext('Mentions that JDK is provided by latest Android Studio Installation', () async { + // Mock a pass through scenario to reach _checkJavaVersion() + sdk + ..licensesAvailable = true + ..platformToolsAvailable = true + ..cmdlineToolsAvailable = true + ..directory = fileSystem.directory('/foo/bar') + ..sdkManagerPath = '/foo/bar/sdkmanager'; + + final ValidationResult validationResult = await AndroidValidator( + java: FakeJava(), + androidSdk: sdk, + logger: logger, + platform: FakePlatform(), + userMessages: UserMessages() + ).validate(); + + expect( + validationResult.messages.any( + (ValidationMessage message) => message.message.contains( + 'This is the JDK bundled with the latest Android Studio installation on this machine.' + ) + ), + true, + ); + expect( + validationResult.messages.any( + (ValidationMessage message) => message.message.contains( + 'To manually set the JDK path, use: `flutter config --jdk-dir="path/to/jdk"`.' + ) + ), + true, + ); + }); + + testWithoutContext("Mentions that JDK is provided by user's JAVA_HOME environment variable", () async { + // Mock a pass through scenario to reach _checkJavaVersion() + sdk + ..licensesAvailable = true + ..platformToolsAvailable = true + ..cmdlineToolsAvailable = true + ..directory = fileSystem.directory('/foo/bar') + ..sdkManagerPath = '/foo/bar/sdkmanager'; + + final ValidationResult validationResult = await AndroidValidator( + java: FakeJava(javaSource: JavaSource.javaHome), + androidSdk: sdk, + logger: logger, + platform: FakePlatform(), + userMessages: UserMessages() + ).validate(); + + expect( + validationResult.messages.any( + (ValidationMessage message) => message.message.contains( + 'This JDK is specified by the JAVA_HOME environment variable.' + ) + ), + true, + ); + expect( + validationResult.messages.any( + (ValidationMessage message) => message.message.contains( + 'To manually set the JDK path, use: `flutter config --jdk-dir="path/to/jdk"`' + ) + ), + true, + ); + }); + + testWithoutContext('Mentions that path to Java binary is obtained from PATH', () async { + // Mock a pass through scenario to reach _checkJavaVersion() + sdk + ..licensesAvailable = true + ..platformToolsAvailable = true + ..cmdlineToolsAvailable = true + ..directory = fileSystem.directory('/foo/bar') + ..sdkManagerPath = '/foo/bar/sdkmanager'; + + final ValidationResult validationResult = await AndroidValidator( + java: FakeJava(javaSource: JavaSource.path), + androidSdk: sdk, + logger: logger, + platform: FakePlatform(), + userMessages: UserMessages() + ).validate(); + + expect( + validationResult.messages.any( + (ValidationMessage message) => message.message.contains( + 'This JDK was found in the system PATH.' + ) + ), + true, + ); + expect( + validationResult.messages.any( + (ValidationMessage message) => message.message.contains( + 'To manually set the JDK path, use: `flutter config --jdk-dir="path/to/jdk"`.' + ) + ), + true, + ); + }); + + testWithoutContext('Mentions that JDK is provided by Flutter config', () async { + // Mock a pass through scenario to reach _checkJavaVersion() + sdk + ..licensesAvailable = true + ..platformToolsAvailable = true + ..cmdlineToolsAvailable = true + ..directory = fileSystem.directory('/foo/bar') + ..sdkManagerPath = '/foo/bar/sdkmanager'; + + final ValidationResult validationResult = await AndroidValidator( + java: FakeJava(javaSource: JavaSource.flutterConfig), + androidSdk: sdk, + logger: logger, + platform: FakePlatform(), + userMessages: UserMessages() + ).validate(); + + expect( + validationResult.messages.any( + (ValidationMessage message) => message.message.contains( + 'This JDK is specified in your Flutter configuration.' + ) + ), + true, + ); + expect( + validationResult.messages.any( + (ValidationMessage message) => message.message.contains( + 'To change the current JDK, run: `flutter config --jdk-dir="path/to/jdk"`.' + ) + ), + true, + ); + }); } class FakeAndroidSdk extends Fake implements AndroidSdk { diff --git a/packages/flutter_tools/test/general.shard/android/java_test.dart b/packages/flutter_tools/test/general.shard/android/java_test.dart index 66d8dd9fc10..778e6e19189 100644 --- a/packages/flutter_tools/test/general.shard/android/java_test.dart +++ b/packages/flutter_tools/test/general.shard/android/java_test.dart @@ -44,6 +44,7 @@ void main() { final AndroidStudio androidStudio = _FakeAndroidStudioWithJdk(); final String androidStudioBundledJdkHome = androidStudio.javaPath!; final String expectedJavaBinaryPath = fs.path.join(androidStudioBundledJdkHome, 'bin', 'java'); + const JavaSource expectedJavaHomeSource = JavaSource.androidStudio; processManager.addCommand(FakeCommand( command: [ @@ -70,12 +71,14 @@ OpenJDK 64-Bit Server VM Zulu19.32+15-CA (build 19.0.2+7, mixed mode, sharing) expect(java.version!.toString(), 'OpenJDK Runtime Environment Zulu19.32+15-CA (build 19.0.2+7)'); expect(java.version, equals(Version(19, 0, 2))); + expect(java.javaSource, expectedJavaHomeSource); }); testWithoutContext('finds JAVA_HOME if it is set and the JDK bundled with Android Studio could not be found', () { final AndroidStudio androidStudio = _FakeAndroidStudioWithoutJdk(); const String javaHome = '/java/home'; final String expectedJavaBinaryPath = fs.path.join(javaHome, 'bin', 'java'); + const JavaSource expectedJavaHomeSource = JavaSource.javaHome; final Java java = Java.find( config: config, @@ -90,11 +93,14 @@ OpenJDK 64-Bit Server VM Zulu19.32+15-CA (build 19.0.2+7, mixed mode, sharing) expect(java.javaHome, javaHome); expect(java.binaryPath, expectedJavaBinaryPath); + expect(java.javaSource, expectedJavaHomeSource); }); testWithoutContext('returns the java binary found on PATH if no other can be found', () { final AndroidStudio androidStudio = _FakeAndroidStudioWithoutJdk(); final OperatingSystemUtils os = _FakeOperatingSystemUtilsWithJava(fileSystem); + const JavaSource expectedJavaHomeSource = JavaSource.path; + processManager.addCommand( const FakeCommand( @@ -114,6 +120,7 @@ OpenJDK 64-Bit Server VM Zulu19.32+15-CA (build 19.0.2+7, mixed mode, sharing) expect(java.javaHome, isNull); expect(java.binaryPath, os.which('java')!.path); + expect(java.javaSource, expectedJavaHomeSource); }); testWithoutContext('returns null if no java could be found', () { @@ -138,6 +145,7 @@ OpenJDK 64-Bit Server VM Zulu19.32+15-CA (build 19.0.2+7, mixed mode, sharing) testWithoutContext('finds and prefers JDK found at config item "jdk-dir" if it is set', () { const String configuredJdkPath = '/jdk'; config.setValue('jdk-dir', configuredJdkPath); + JavaSource expectedJavaHomeSource = JavaSource.flutterConfig; processManager.addCommand( const FakeCommand( @@ -164,9 +172,12 @@ OpenJDK 64-Bit Server VM Zulu19.32+15-CA (build 19.0.2+7, mixed mode, sharing) expect(java, isNotNull); expect(java!.javaHome, configuredJdkPath); expect(java.binaryPath, fs.path.join(configuredJdkPath, 'bin', 'java')); + expect(java.javaSource, expectedJavaHomeSource); config.removeValue('jdk-dir'); + expectedJavaHomeSource = JavaSource.androidStudio; + java = Java.find( config: config, androidStudio: androidStudio, @@ -180,6 +191,7 @@ OpenJDK 64-Bit Server VM Zulu19.32+15-CA (build 19.0.2+7, mixed mode, sharing) assert(androidStudio.javaPath != configuredJdkPath); expect(java!.javaHome, androidStudio.javaPath); expect(java.binaryPath, fs.path.join(androidStudio.javaPath!, 'bin', 'java')); + expect(java.javaSource, expectedJavaHomeSource); }); }); @@ -196,6 +208,7 @@ OpenJDK 64-Bit Server VM Zulu19.32+15-CA (build 19.0.2+7, mixed mode, sharing) processManager: processManager, binaryPath: 'javaHome/bin/java', javaHome: 'javaHome', + javaSource: JavaSource.javaHome, ); }); diff --git a/packages/flutter_tools/test/general.shard/args_test.dart b/packages/flutter_tools/test/general.shard/args_test.dart index 08997eae2a4..65eed6102b0 100644 --- a/packages/flutter_tools/test/general.shard/args_test.dart +++ b/packages/flutter_tools/test/general.shard/args_test.dart @@ -232,7 +232,6 @@ void verifyOptions(String? command, Iterable