From c8510f29ccc2cefaf1337a7ba81192e34dd87b32 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Fri, 8 Nov 2024 10:32:29 -0500 Subject: [PATCH 001/386] Roll Flutter Engine from 44d788f4651b to a08bd5a07c2a (3 revisions) (#158375) https://github.com/flutter/engine/compare/44d788f4651b...a08bd5a07c2a 2024-11-08 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from pG2aukmcwvp71aKuS... to aLUsXLv5iMZFOgcAS... (flutter/engine#56450) 2024-11-08 skia-flutter-autoroll@skia.org Roll Skia from 7ae36ecfe93d to d0ee80612f86 (2 revisions) (flutter/engine#56448) 2024-11-08 codefu@google.com Move off deprecated upload-artifactv3 (flutter/engine#56439) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from pG2aukmcwvp7 to aLUsXLv5iMZF If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jsimmons@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index b0eeac553b6..246d48956c4 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -44d788f4651be9addc9cbca34ac2da7fdba80648 +a08bd5a07c2ac8e160e286c5841f47fa801e823b diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index 187300c87eb..c9b3a7543d6 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -pG2aukmcwvp71aKuS7CLjA4I9qz5FE1c2Spyk7WPYL4C +aLUsXLv5iMZFOgcASHyt85mUrltN-l30HDAFfAX5bAUC From e222381e295937206ed646c757b980026d8f2edb Mon Sep 17 00:00:00 2001 From: Phil Quitslund Date: Fri, 8 Nov 2024 09:30:26 -0800 Subject: [PATCH 002/386] remove redundant arguments (#158349) An upcoming fix to the analyzer will (correctly) catch these args as redundant (https://dart-review.googlesource.com/c/sdk/+/394004/2/pkg/analyzer/lib/src/dart/ast/ast.dart). ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [ ] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- packages/flutter_tools/bin/fuchsia_asset_builder.dart | 2 +- packages/flutter_tools/bin/fuchsia_tester.dart | 2 +- packages/flutter_tools/test/src/context.dart | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/flutter_tools/bin/fuchsia_asset_builder.dart b/packages/flutter_tools/bin/fuchsia_asset_builder.dart index 8f2d840ba0c..803b6ef45bd 100644 --- a/packages/flutter_tools/bin/fuchsia_asset_builder.dart +++ b/packages/flutter_tools/bin/fuchsia_asset_builder.dart @@ -34,7 +34,7 @@ const List _kRequiredOptions = [ Future main(List args) { return runInContext(() => run(args), overrides: { Usage: () => DisabledUsage(), - }, useImplicitPubspecResolution: true); + }); } 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..00a379e6ece 100644 --- a/packages/flutter_tools/bin/fuchsia_tester.dart +++ b/packages/flutter_tools/bin/fuchsia_tester.dart @@ -43,7 +43,7 @@ const String _kOptionCoveragePath = 'coverage-path'; void main(List args) { runInContext(() => run(args), overrides: { Usage: () => DisabledUsage(), - }, useImplicitPubspecResolution: true); + }); } Future run(List args) async { diff --git a/packages/flutter_tools/test/src/context.dart b/packages/flutter_tools/test/src/context.dart index e18af3f34fb..8207b601da8 100644 --- a/packages/flutter_tools/test/src/context.dart +++ b/packages/flutter_tools/test/src/context.dart @@ -183,7 +183,7 @@ void testUsingContext( // can provide the AlwaysFalseBotDetector in the overrides, or its own // BotDetector implementation in the overrides. BotDetector: overrides[BotDetector] ?? () => const FakeBotDetector(true), - }, useImplicitPubspecResolution: true); + }); }, testOn: testOn, skip: skip); // We don't support "timeout"; see ../../dart_test.yaml which // configures all tests to have a 15 minute timeout which should From 1511370a92ea81a2e47ea27470d3748df75ac324 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Stein?= Date: Fri, 8 Nov 2024 15:26:05 -0300 Subject: [PATCH 003/386] [TextInput] Add TextInputType.webSearch (#15762) (#158323) This PR adds `TextInputType.webSearch` that allows to show a keyboard with ready access to a "." key on iOS. On Android this is re-mapped to `url` which shows the same behaviour as `webSearch` on iOS. This fixes issue #157562. There also is a [corresponding *engine* PR](https://github.com/flutter/engine/pull/56428). Screenshot from iOS demo app: ![image](https://github.com/user-attachments/assets/94d48752-4cfe-4113-acf9-b3a981952dc7) --- packages/flutter/lib/src/services/text_input.dart | 14 ++++++++++++-- .../flutter/test/services/text_input_test.dart | 2 ++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/packages/flutter/lib/src/services/text_input.dart b/packages/flutter/lib/src/services/text_input.dart index eb8d91a5426..890b4933f44 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. 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})'); From 2efdc747920b5ce87dddbb4444a5ae7da8441ede Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Fri, 8 Nov 2024 14:55:12 -0500 Subject: [PATCH 004/386] Roll Flutter Engine from a08bd5a07c2a to 1b567e80386e (1 revision) (#158393) https://github.com/flutter/engine/compare/a08bd5a07c2a...1b567e80386e 2024-11-08 jason-simmons@users.noreply.github.com In the embedder Impeller render target, use a multisample texture for the depth buffer only if MSAA is supported (flutter/engine#56444) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jsimmons@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 246d48956c4..f55b894d4c9 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -a08bd5a07c2ac8e160e286c5841f47fa801e823b +1b567e80386e22705f86908848245ff46643eb05 From d6918a48d3bb8c247efabea04b3361e1c4a40e02 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Fri, 8 Nov 2024 16:43:05 -0500 Subject: [PATCH 005/386] Roll Flutter Engine from 1b567e80386e to 6b77347edfc5 (4 revisions) (#158398) https://github.com/flutter/engine/compare/1b567e80386e...6b77347edfc5 2024-11-08 chris@bracken.jp Add FlutterTaskRunnerDescription.destruction_callback (flutter/engine#56445) 2024-11-08 skia-flutter-autoroll@skia.org Roll Skia from d0ee80612f86 to 778b21720a61 (5 revisions) (flutter/engine#56457) 2024-11-08 skia-flutter-autoroll@skia.org Manual roll Dart SDK from 50c620224f27 to cfa1826c3df1 (2 revisions) (flutter/engine#56456) 2024-11-08 flar@google.com [Impeller] Switch to uniform arrays for gradient data on non-SSBO hardware (flutter/engine#56441) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jsimmons@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index f55b894d4c9..961086b4690 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -1b567e80386e22705f86908848245ff46643eb05 +6b77347edfc5b96fe32752392180e9f202a05759 From fdbfbca12a8cb4301c5638130393237123982830 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Fri, 8 Nov 2024 17:28:24 -0500 Subject: [PATCH 006/386] Roll Flutter Engine from 6b77347edfc5 to b7134d373ef8 (3 revisions) (#158402) https://github.com/flutter/engine/compare/6b77347edfc5...b7134d373ef8 2024-11-08 chris@bracken.jp fml: Use CFRef where possible and add docs (flutter/engine#56436) 2024-11-08 mdebbar@google.com [web] Split all 1MB+ fallback fonts (including CJK) (flutter/engine#56388) 2024-11-08 chris@bracken.jp yapf: Add more detailed error message and TODO (flutter/engine#56458) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jsimmons@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 961086b4690..30fbc5a54a6 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -6b77347edfc5b96fe32752392180e9f202a05759 +b7134d373ef8f73da4fc5764a1d5bd6d02265ff0 From d8334d53d7535d8603b550ebcbf229c363287ea8 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Fri, 8 Nov 2024 18:22:12 -0500 Subject: [PATCH 007/386] Roll Flutter Engine from b7134d373ef8 to 54df0b8a4784 (2 revisions) (#158405) https://github.com/flutter/engine/compare/b7134d373ef8...54df0b8a4784 2024-11-08 rosscomputerguy@protonmail.com [Linux] Replace deprecated macros in fl_application_test.cc (flutter/engine#56257) 2024-11-08 jonahwilliams@google.com [iOS] fix tracking of previous platform views. (flutter/engine#56461) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jsimmons@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 30fbc5a54a6..3da562e164e 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -b7134d373ef8f73da4fc5764a1d5bd6d02265ff0 +54df0b8a478487c863b2bc112447bc85f5740638 From bf1fac785e79c53e0bb55261f8b96fb82eb914a8 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Fri, 8 Nov 2024 19:16:06 -0500 Subject: [PATCH 008/386] Roll Flutter Engine from 54df0b8a4784 to 2f097cfd3d2d (1 revision) (#158407) https://github.com/flutter/engine/compare/54df0b8a4784...2f097cfd3d2d 2024-11-08 a-siva@users.noreply.github.com Manual roll Dart SDK from cfa1826c3df1 to 307869c696e8 (1 revision) (flutter/engine#56460) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jsimmons@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 3da562e164e..9b3f27f5cdc 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -54df0b8a478487c863b2bc112447bc85f5740638 +2f097cfd3d2dc64dd86643e347e33b7642d14399 From 995ff31bbd5e04810f0bc8d9db6c48b4ef5676ab Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Fri, 8 Nov 2024 22:07:32 -0500 Subject: [PATCH 009/386] Roll Flutter Engine from 2f097cfd3d2d to ca6f5110d9d3 (3 revisions) (#158411) https://github.com/flutter/engine/compare/2f097cfd3d2d...ca6f5110d9d3 2024-11-09 chris@bracken.jp iOS: Use fml::CFRef in place of Scoped (flutter/engine#56463) 2024-11-09 skia-flutter-autoroll@skia.org Roll Dart SDK from 307869c696e8 to ed9a5b1110ae (2 revisions) (flutter/engine#56465) 2024-11-08 chris@bracken.jp fml: delete unused scoped_policy (flutter/engine#56462) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jsimmons@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 9b3f27f5cdc..9eb2eaf733b 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -2f097cfd3d2dc64dd86643e347e33b7642d14399 +ca6f5110d9d34c1303a1d0718431018b88942eec From fca4f88b958443ffc7b3632155010efa54dd50c0 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sat, 9 Nov 2024 11:09:23 -0500 Subject: [PATCH 010/386] Roll Flutter Engine from ca6f5110d9d3 to 690cdfd09beb (1 revision) (#158414) https://github.com/flutter/engine/compare/ca6f5110d9d3...690cdfd09beb 2024-11-09 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from aLUsXLv5iMZFOgcAS... to TZVo85tD5mpzhcafg... (flutter/engine#56478) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from aLUsXLv5iMZF to TZVo85tD5mpz If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jsimmons@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 9eb2eaf733b..f84d24e4016 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -ca6f5110d9d34c1303a1d0718431018b88942eec +690cdfd09beba0c7900b177d802b29dad22a9e80 diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index c9b3a7543d6..13b658c01a6 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -aLUsXLv5iMZFOgcASHyt85mUrltN-l30HDAFfAX5bAUC +TZVo85tD5mpzhcafgVvi5wlAXomXRbtrbCfGJ2tO_ogC From 893a0c8fcd506016667b42a9bdd1414179a321d9 Mon Sep 17 00:00:00 2001 From: Flutter GitHub Bot Date: Sat, 9 Nov 2024 14:45:40 -0500 Subject: [PATCH 011/386] Marks Mac_benchmark complex_layout_scroll_perf_macos__timeline_summary to be flaky (#158252) Issue link: https://github.com/flutter/flutter/issues/158251 --- .ci.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.ci.yaml b/.ci.yaml index d44bd12b28f..5a4d7440021 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -3828,6 +3828,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 From 286eb1303c7cd2dcbda31504433fa890e98b28ba Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sat, 9 Nov 2024 17:03:26 -0500 Subject: [PATCH 012/386] Roll Flutter Engine from 690cdfd09beb to 9b4c3b3d5518 (1 revision) (#158418) https://github.com/flutter/engine/compare/690cdfd09beb...9b4c3b3d5518 2024-11-09 jason-simmons@users.noreply.github.com Remove the unsafe_html analysis rule (flutter/engine#56479) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jsimmons@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index f84d24e4016..f346b9b5f36 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -690cdfd09beba0c7900b177d802b29dad22a9e80 +9b4c3b3d5518c847e188e2d373e77f081b9ed812 From c9eb4ae9cc6f4716c91ffa37636f5898a6648de7 Mon Sep 17 00:00:00 2001 From: Andrew Kolos Date: Sun, 10 Nov 2024 13:49:24 -0800 Subject: [PATCH 013/386] remove `bringup` status for recently re-subsharded targets (#158217) Cleans up https://github.com/flutter/flutter/pull/158196 and https://github.com/flutter/flutter/pull/158146
Pre-launch checklist
--- .ci.yaml | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/.ci.yaml b/.ci.yaml index 5a4d7440021..c0e7717f646 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -1170,7 +1170,6 @@ targets: - .ci.yaml - name: Linux tool_integration_tests_1_6 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -1197,7 +1196,6 @@ targets: - .ci.yaml - name: Linux tool_integration_tests_2_6 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -1224,7 +1222,6 @@ targets: - .ci.yaml - name: Linux tool_integration_tests_3_6 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -1251,7 +1248,6 @@ targets: - .ci.yaml - name: Linux tool_integration_tests_4_6 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -1278,7 +1274,6 @@ targets: - .ci.yaml - name: Linux tool_integration_tests_5_6 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -1305,7 +1300,6 @@ targets: - .ci.yaml - name: Linux tool_integration_tests_6_6 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -5418,7 +5412,6 @@ targets: task_name: run_release_test_macos - name: Windows build_tests_1_9 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -5437,7 +5430,6 @@ targets: ["framework", "hostonly", "shard", "windows"] - name: Windows build_tests_2_9 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -5456,7 +5448,6 @@ targets: ["framework", "hostonly", "shard", "windows"] - name: Windows build_tests_3_9 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -5475,7 +5466,6 @@ targets: ["framework", "hostonly", "shard", "windows"] - name: Windows build_tests_4_9 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -5494,7 +5484,6 @@ targets: ["framework", "hostonly", "shard", "windows"] - name: Windows build_tests_5_9 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -5513,7 +5502,6 @@ targets: ["framework", "hostonly", "shard", "windows"] - name: Windows build_tests_6_9 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -5532,7 +5520,6 @@ targets: ["framework", "hostonly", "shard", "windows"] - name: Windows build_tests_7_9 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -5551,7 +5538,6 @@ targets: ["framework", "hostonly", "shard", "windows"] - name: Windows build_tests_8_9 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: @@ -5570,7 +5556,6 @@ targets: ["framework", "hostonly", "shard", "windows"] - name: Windows build_tests_9_9 - bringup: true recipe: flutter/flutter_drone timeout: 60 properties: From f04b0f4b9e5af3241c888820923957e52c6c5979 Mon Sep 17 00:00:00 2001 From: Flutter GitHub Bot Date: Sun, 10 Nov 2024 17:30:39 -0500 Subject: [PATCH 014/386] Marks Linux analyzer_benchmark to be flaky (#158244) Issue link: https://github.com/flutter/flutter/issues/158243 --- .ci.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.ci.yaml b/.ci.yaml index c0e7717f646..1f681011e38 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -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: From 1eaf1f9525008059a44ef6dd5c7e2f4cb2257dd1 Mon Sep 17 00:00:00 2001 From: Nate Wilson Date: Sun, 10 Nov 2024 18:00:21 -0700 Subject: [PATCH 015/386] Add `SafeArea` DartPad sample (#158019) Follow-up from #157228 --- .../lib/widgets/safe_area/safe_area.0.dart | 288 ++++++++++++++++++ .../widgets/safe_area/safe_area.0_test.dart | 84 +++++ .../flutter/lib/src/widgets/safe_area.dart | 13 +- 3 files changed, 379 insertions(+), 6 deletions(-) create mode 100644 examples/api/lib/widgets/safe_area/safe_area.0.dart create mode 100644 examples/api/test/widgets/safe_area/safe_area.0_test.dart 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..3c3f8779373 --- /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, + contentPadding: EdgeInsets.all(6.0), + ), + 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: 14), + 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/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..a0bf4c3d22f --- /dev/null +++ b/examples/api/test/widgets/safe_area/safe_area.0_test.dart @@ -0,0 +1,84 @@ +// 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); + }); +} diff --git a/packages/flutter/lib/src/widgets/safe_area.dart b/packages/flutter/lib/src/widgets/safe_area.dart index 023e8fe1f1e..e84164c0f42 100644 --- a/packages/flutter/lib/src/widgets/safe_area.dart +++ b/packages/flutter/lib/src/widgets/safe_area.dart @@ -16,15 +16,16 @@ 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 From 18071ec0a87c281edffa0179228560dfe1f6f357 Mon Sep 17 00:00:00 2001 From: Younghan Kim Date: Mon, 11 Nov 2024 11:47:32 +0900 Subject: [PATCH 016/386] Remove block and line comments when detecting '.flutter-plugins' in settings.gradle(.kts) (#155488) **PR Title:** Remove block and line comments when detecting `'.flutter-plugins'` in `settings.gradle` --- **Description:** This PR modifies the `configureLegacyPluginEachProjects` function to remove block (`/* ... */`) and line (`// ...`) comments from the `settings.gradle` or `settings.gradle.kts` file content before checking for the presence of the `'.flutter-plugins'` string. This ensures that only uncommented, meaningful code is considered during the detection, preventing false positives when the string appears within comments. **Why is this change necessary?** In some cases, the `'.flutter-plugins'` string may be present inside comments in the `settings.gradle` file. The existing implementation does not account for this and may incorrectly detect the string even when it's commented out. This can lead to unintended behavior, such as configuring plugin projects when it is not necessary. By removing comments before performing the check, we prevent false positives and ensure that the detection logic is accurate, only acting when the `'.flutter-plugins'` string is present in active code. **Changes Made:** - **Added comment removal logic:** - Removed block comments (`/* ... */`) using the regular expression `/(?s)\/\*.*?\*\//`. - The `(?s)` flag enables dot-all mode, allowing `.` to match newline characters. - Removed line comments (`// ...`) using the regular expression `/(?m)\/\/.*$`. - The `(?m)` flag enables multi-line mode, so `^` and `$` match the start and end of each line. - Combined both comment removal steps into a single chain for efficiency. - **Updated the string detection:** - The check for `'.flutter-plugins'` is now performed on the uncommented content of the `settings.gradle` file. - This ensures that only meaningful, uncommented code is considered during detection. **Issue Fixed:** - Fixes [#155484](https://github.com/flutter/flutter/issues/155484) --- --- If you need any further assistance or have questions, feel free to reach out! --- **Links:** - [Contributor Guide] - [Tree Hygiene] - [Flutter Style Guide] - [Features we expect every widget to implement] - [CLA] - [flutter/tests] - [breaking change policy] - [Discord] - [Data Driven Fixes] --- .../gradle/src/main/groovy/flutter.groovy | 7 +- ...tter_plugins_strings_in_comments_test.dart | 98 +++++++++++++++++++ 2 files changed, 104 insertions(+), 1 deletion(-) create mode 100644 packages/flutter_tools/test/integration.shard/android_gradle_legacy_flutter_plugins_strings_in_comments_test.dart diff --git a/packages/flutter_tools/gradle/src/main/groovy/flutter.groovy b/packages/flutter_tools/gradle/src/main/groovy/flutter.groovy index 4949b597fc0..f1661ec0dac 100644 --- a/packages/flutter_tools/gradle/src/main/groovy/flutter.groovy +++ b/packages/flutter_tools/gradle/src/main/groovy/flutter.groovy @@ -677,7 +677,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) { diff --git a/packages/flutter_tools/test/integration.shard/android_gradle_legacy_flutter_plugins_strings_in_comments_test.dart b/packages/flutter_tools/test/integration.shard/android_gradle_legacy_flutter_plugins_strings_in_comments_test.dart new file mode 100644 index 00000000000..d5d7a46d7c9 --- /dev/null +++ b/packages/flutter_tools/test/integration.shard/android_gradle_legacy_flutter_plugins_strings_in_comments_test.dart @@ -0,0 +1,98 @@ +// 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 test can be removed once https://github.com/flutter/flutter/issues/155484 is resolved. + +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; +import 'package:flutter_tools/src/cache.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + + setUp(() { + Cache.flutterRoot = getFlutterRoot(); + tempDir = createResolvedTempDirectorySync('flutter_plugin_test.'); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + test('should build Android app with commented-out ".flutter-plugins" in settings.gradle', () async { + final String flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + + // Create Android app project instead of plugin + processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'create', + '--template=app', + 'test_android_app', + ], workingDirectory: tempDir.path); + + final Directory appDir = tempDir.childDirectory('test_android_app'); + final Directory androidDir = appDir.childDirectory('android'); + + // Create settings.gradle with commented .flutter-plugins + final File settingsGradle = androidDir.childFile('settings.gradle'); + settingsGradle.writeAsStringSync(r''' +// The following block uses '.flutter-plugins' but is commented out. +/* +def plugins = new Properties() +def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins') +if (pluginsFile.exists()) { + pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) } +} +*/ + +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.application" version "8.1.0" apply false + id "org.jetbrains.kotlin.android" version "1.8.22" apply false +} + +include ":app" +'''); + + // Run flutter build apk with release mode + final ProcessResult buildApkResult = await processManager.run([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'apk', + '--release', + ], workingDirectory: appDir.path); + + // Build should succeed and not throw any errors about settings.gradle + expect(buildApkResult.stderr.toString(), + isNot(contains('Please fix your settings.gradle'))); + expect(buildApkResult, const ProcessResultMatcher()); + }); +} From 5fd650f68b9c644ebd122b2283d020e0bbb2a40e Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sun, 10 Nov 2024 23:02:25 -0500 Subject: [PATCH 017/386] Roll Flutter Engine from 9b4c3b3d5518 to 01c76e42c20f (3 revisions) (#158438) https://github.com/flutter/engine/compare/9b4c3b3d5518...01c76e42c20f 2024-11-11 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from TZVo85tD5mpzhcafg... to BajfrJuYeyWvnBhuM... (flutter/engine#56497) 2024-11-11 skia-flutter-autoroll@skia.org Roll Skia from 778b21720a61 to 3333292a62c1 (7 revisions) (flutter/engine#56496) 2024-11-10 chris@bracken.jp fml: Improve CFTest.SupportsCustomRetainRelease test (flutter/engine#56480) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from TZVo85tD5mpz to BajfrJuYeyWv If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jsimmons@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index f346b9b5f36..e1a19dca236 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -9b4c3b3d5518c847e188e2d373e77f081b9ed812 +01c76e42c20f96fd86d5b4ff66228f5f935d9e90 diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index 13b658c01a6..c829a3a8c57 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -TZVo85tD5mpzhcafgVvi5wlAXomXRbtrbCfGJ2tO_ogC +BajfrJuYeyWvnBhuMsYlPmNADNd_e4gS4bvqpD0uDTsC From 461ad0d3e0f9ceeabb78f09d1f14126e3ecb3d7d Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Mon, 11 Nov 2024 04:44:04 -0500 Subject: [PATCH 018/386] Roll Flutter Engine from 01c76e42c20f to d90e9f4718b8 (1 revision) (#158443) https://github.com/flutter/engine/compare/01c76e42c20f...d90e9f4718b8 2024-11-11 skia-flutter-autoroll@skia.org Roll Skia from 3333292a62c1 to 676b3b1a41be (2 revisions) (flutter/engine#56499) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jsimmons@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index e1a19dca236..d7d503a0fc4 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -01c76e42c20f96fd86d5b4ff66228f5f935d9e90 +d90e9f4718b811c73b7f4288cfb34aea2c6cd529 From 232706616a306eecf9cfd4c144cc91be70c15f44 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Mon, 11 Nov 2024 09:36:26 -0500 Subject: [PATCH 019/386] Roll Flutter Engine from d90e9f4718b8 to e9a44820f302 (1 revision) (#158453) https://github.com/flutter/engine/compare/d90e9f4718b8...e9a44820f302 2024-11-11 skia-flutter-autoroll@skia.org Roll Dart SDK from ed9a5b1110ae to cde0e0dc084a (6 revisions) (flutter/engine#56500) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jsimmons@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index d7d503a0fc4..700fee7f31f 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -d90e9f4718b811c73b7f4288cfb34aea2c6cd529 +e9a44820f3021dbac75f0a6360882a716b11544e From d89e65d51647b880147624cc78e4e3d573956288 Mon Sep 17 00:00:00 2001 From: Ben Konyi Date: Mon, 11 Nov 2024 10:18:09 -0500 Subject: [PATCH 020/386] Replace custom `RPCErrorCodes` with `RPCErrorKind` from `package:vm_service` (#158379) Removes duplicated constants and ensures consistency by using package:vm_service as a source of truth for RPC error codes for requests made with package:vm_service. --- .../lib/src/commands/attach.dart | 3 +- .../flutter_tools/lib/src/commands/run.dart | 3 +- packages/flutter_tools/lib/src/devfs.dart | 2 +- packages/flutter_tools/lib/src/run_hot.dart | 4 +- packages/flutter_tools/lib/src/vmservice.dart | 42 +++----------- .../commands.shard/hermetic/attach_test.dart | 7 +-- .../commands.shard/hermetic/run_test.dart | 7 +-- .../test/general.shard/devfs_test.dart | 10 ++-- .../resident_devtools_handler_test.dart | 9 +-- .../general.shard/resident_runner_test.dart | 4 +- .../resident_web_runner_test.dart | 9 ++- .../general.shard/terminal_handler_test.dart | 6 +- .../test/general.shard/tracing_test.dart | 4 +- .../test/general.shard/vmservice_test.dart | 56 +++++++++---------- 14 files changed, 71 insertions(+), 95 deletions(-) diff --git a/packages/flutter_tools/lib/src/commands/attach.dart b/packages/flutter_tools/lib/src/commands/attach.dart index b149f72000f..84cb841fc95 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`. @@ -415,7 +414,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.'); } diff --git a/packages/flutter_tools/lib/src/commands/run.dart b/packages/flutter_tools/lib/src/commands/run.dart index 10fbe0914e0..db44e62c94e 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'; @@ -866,7 +865,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/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/run_hot.dart b/packages/flutter_tools/lib/src/run_hot.dart index 79634f75ca3..733c7c8ec5b 100644 --- a/packages/flutter_tools/lib/src/run_hot.dart +++ b/packages/flutter_tools/lib/src/run_hot.dart @@ -176,7 +176,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 +188,7 @@ class HotRunner extends ResidentRunner { if (!result.isOk) { throw vm_service.RPCError( 'Unable to restart', - RPCErrorCodes.kInternalError, + vm_service.RPCErrorKind.kInternalError.code, '', ); } diff --git a/packages/flutter_tools/lib/src/vmservice.dart b/packages/flutter_tools/lib/src/vmservice.dart index 98ae0bcdf80..bd02578ea87 100644 --- a/packages/flutter_tools/lib/src/vmservice.dart +++ b/packages/flutter_tools/lib/src/vmservice.dart @@ -58,29 +58,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 @@ -424,7 +401,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 +413,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 +475,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 +496,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 +566,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 +866,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 +1005,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 +1021,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); 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..175239ea501 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]; 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..ae038dd3ffa 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/run_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/run_test.dart @@ -29,7 +29,6 @@ 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; @@ -1129,7 +1128,7 @@ void main() { final FakeResidentRunner residentRunner = FakeResidentRunner(); residentRunner.rpcError = RPCError( 'flutter._listViews', - RPCErrorCodes.kServiceDisappeared, + RPCErrorKind.kServiceDisappeared.code, '', ); final TestRunCommandWithFakeResidentRunner command = TestRunCommandWithFakeResidentRunner(); @@ -1142,7 +1141,7 @@ void main() { residentRunner.rpcError = RPCError( 'flutter._listViews', - RPCErrorCodes.kServerError, + RPCErrorKind.kServerError.code, 'Service connection disposed.', ); @@ -1158,7 +1157,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; diff --git a/packages/flutter_tools/test/general.shard/devfs_test.dart b/packages/flutter_tools/test/general.shard/devfs_test.dart index 8ab44c81144..2e4f1297888 100644 --- a/packages/flutter_tools/test/general.shard/devfs_test.dart +++ b/packages/flutter_tools/test/general.shard/devfs_test.dart @@ -24,9 +24,9 @@ import 'package:flutter_tools/src/build_system/tools/shader_compiler.dart'; import 'package:flutter_tools/src/compile.dart'; import 'package:flutter_tools/src/devfs.dart'; import 'package:flutter_tools/src/flutter_manifest.dart'; -import 'package:flutter_tools/src/vmservice.dart'; import 'package:package_config/package_config.dart'; import 'package:test/fake.dart'; +import 'package:vm_service/vm_service.dart' as vm_service; import '../src/common.dart'; import '../src/context.dart'; @@ -46,18 +46,18 @@ final FakeVmServiceRequest createDevFSRequest = FakeVmServiceRequest( } ); -const FakeVmServiceRequest failingCreateDevFSRequest = FakeVmServiceRequest( +FakeVmServiceRequest failingCreateDevFSRequest = FakeVmServiceRequest( method: '_createDevFS', args: { 'fsName': 'test', }, - error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + error: FakeRPCError(code: vm_service.RPCErrorKind.kServiceDisappeared.code), ); -const FakeVmServiceRequest failingDeleteDevFSRequest = FakeVmServiceRequest( +FakeVmServiceRequest failingDeleteDevFSRequest = FakeVmServiceRequest( method: '_deleteDevFS', args: {'fsName': 'test'}, - error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + error: FakeRPCError(code: vm_service.RPCErrorKind.kServiceDisappeared.code), ); void main() { diff --git a/packages/flutter_tools/test/general.shard/resident_devtools_handler_test.dart b/packages/flutter_tools/test/general.shard/resident_devtools_handler_test.dart index e99ae741efc..c2f7ad2bf51 100644 --- a/packages/flutter_tools/test/general.shard/resident_devtools_handler_test.dart +++ b/packages/flutter_tools/test/general.shard/resident_devtools_handler_test.dart @@ -16,6 +16,7 @@ import 'package:flutter_tools/src/resident_runner.dart'; import 'package:flutter_tools/src/vmservice.dart'; import 'package:test/fake.dart'; import 'package:vm_service/vm_service.dart' as vm_service; +import 'package:vm_service/vm_service.dart'; import '../src/common.dart'; import '../src/fake_process_manager.dart'; @@ -254,9 +255,9 @@ void main() { 'streamId': 'Isolate', }, ), - const FakeVmServiceRequest( + FakeVmServiceRequest( method: kListViewsMethod, - error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + error: FakeRPCError(code: RPCErrorKind.kServiceDisappeared.code), ), ], httpAddress: Uri.parse('http://localhost:1234')); @@ -317,9 +318,9 @@ void main() { 'streamId': 'Isolate', }, ), - const FakeVmServiceRequest( + FakeVmServiceRequest( method: kListViewsMethod, - error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + error: FakeRPCError(code: RPCErrorKind.kServiceDisappeared.code), ), ], httpAddress: Uri.parse('http://localhost:5678')); diff --git a/packages/flutter_tools/test/general.shard/resident_runner_test.dart b/packages/flutter_tools/test/general.shard/resident_runner_test.dart index 95bdd3168ef..6e619fd2ff8 100644 --- a/packages/flutter_tools/test/general.shard/resident_runner_test.dart +++ b/packages/flutter_tools/test/general.shard/resident_runner_test.dart @@ -1958,10 +1958,10 @@ flutter: testUsingContext('FlutterDevice does not throw when unable to initiate log reader due to VM service disconnection', () async { fakeVmServiceHost = FakeVmServiceHost( requests: [ - const FakeVmServiceRequest( + FakeVmServiceRequest( method: 'getVM', error: FakeRPCError( - code: RPCErrorCodes.kServerError, + code: vm_service.RPCErrorKind.kServerError.code, error: 'Service connection disposed', ), ), diff --git a/packages/flutter_tools/test/general.shard/resident_web_runner_test.dart b/packages/flutter_tools/test/general.shard/resident_web_runner_test.dart index 5af054eed8b..108306f7114 100644 --- a/packages/flutter_tools/test/general.shard/resident_web_runner_test.dart +++ b/packages/flutter_tools/test/general.shard/resident_web_runner_test.dart @@ -979,10 +979,10 @@ void main() { final ResidentRunner residentWebRunner = setUpResidentRunner(flutterDevice); fakeVmServiceHost = FakeVmServiceHost(requests: [ ...kAttachExpectations, - const FakeVmServiceRequest( + FakeVmServiceRequest( method: kHotRestartServiceName, // Failed response, - error: FakeRPCError(code: RPCErrorCodes.kInternalError), + error: FakeRPCError(code: vm_service.RPCErrorKind.kInternalError.code), ), ]); setupMocks(); @@ -995,7 +995,10 @@ void main() { final OperationResult result = await residentWebRunner.restart(); expect(result.code, 1); - expect(result.message, contains(RPCErrorCodes.kInternalError.toString())); + expect( + result.message, + contains(vm_service.RPCErrorKind.kInternalError.code.toString()), + ); }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => processManager, diff --git a/packages/flutter_tools/test/general.shard/terminal_handler_test.dart b/packages/flutter_tools/test/general.shard/terminal_handler_test.dart index 6a97247298d..f392e90a494 100644 --- a/packages/flutter_tools/test/general.shard/terminal_handler_test.dart +++ b/packages/flutter_tools/test/general.shard/terminal_handler_test.dart @@ -1118,10 +1118,10 @@ void main() { 'enabled': 'false', }, ), - const FakeVmServiceRequest( + FakeVmServiceRequest( method: 'ext.dwds.screenshot', // Failed response, - error: FakeRPCError(code: RPCErrorCodes.kInternalError), + error: FakeRPCError(code: vm_service.RPCErrorKind.kInternalError.code), ), FakeVmServiceRequest( method: 'ext.flutter.debugAllowBanner', @@ -1161,7 +1161,7 @@ void main() { 'enabled': 'true', }, // Failed response, - error: const FakeRPCError(code: RPCErrorCodes.kInternalError), + error: FakeRPCError(code: vm_service.RPCErrorKind.kInternalError.code), ), ], logger: logger, diff --git a/packages/flutter_tools/test/general.shard/tracing_test.dart b/packages/flutter_tools/test/general.shard/tracing_test.dart index e7719b26e63..a3145fac053 100644 --- a/packages/flutter_tools/test/general.shard/tracing_test.dart +++ b/packages/flutter_tools/test/general.shard/tracing_test.dart @@ -138,9 +138,9 @@ void main() { final FileSystem fileSystem = MemoryFileSystem.test(); final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ ...vmServiceSetup, - const FakeVmServiceRequest( + FakeVmServiceRequest( method: 'getVMTimeline', - error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + error: FakeRPCError(code: vm_service.RPCErrorKind.kServiceDisappeared.code), ), const FakeVmServiceRequest( method: 'setVMTimelineFlags', diff --git a/packages/flutter_tools/test/general.shard/vmservice_test.dart b/packages/flutter_tools/test/general.shard/vmservice_test.dart index d4e7f901402..0ab47d859a0 100644 --- a/packages/flutter_tools/test/general.shard/vmservice_test.dart +++ b/packages/flutter_tools/test/general.shard/vmservice_test.dart @@ -263,12 +263,12 @@ void main() { testWithoutContext('flutterDebugDumpSemanticsTreeInTraversalOrder handles missing method', () async { final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( requests: [ - const FakeVmServiceRequest( + FakeVmServiceRequest( method: 'ext.flutter.debugDumpSemanticsTreeInTraversalOrder', args: { 'isolateId': '1', }, - error: FakeRPCError(code: RPCErrorCodes.kMethodNotFound), + error: FakeRPCError(code: vm_service.RPCErrorKind.kMethodNotFound.code), ), ] ); @@ -282,12 +282,12 @@ void main() { testWithoutContext('flutterDebugDumpSemanticsTreeInInverseHitTestOrder handles missing method', () async { final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( requests: [ - const FakeVmServiceRequest( + FakeVmServiceRequest( method: 'ext.flutter.debugDumpSemanticsTreeInInverseHitTestOrder', args: { 'isolateId': '1', }, - error: FakeRPCError(code: RPCErrorCodes.kMethodNotFound), + error: FakeRPCError(code: vm_service.RPCErrorKind.kMethodNotFound.code), ), ] ); @@ -301,12 +301,12 @@ void main() { testWithoutContext('flutterDebugDumpLayerTree handles missing method', () async { final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( requests: [ - const FakeVmServiceRequest( + FakeVmServiceRequest( method: 'ext.flutter.debugDumpLayerTree', args: { 'isolateId': '1', }, - error: FakeRPCError(code: RPCErrorCodes.kMethodNotFound), + error: FakeRPCError(code: vm_service.RPCErrorKind.kMethodNotFound.code), ), ] ); @@ -320,12 +320,12 @@ void main() { testWithoutContext('flutterDebugDumpRenderTree handles missing method', () async { final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( requests: [ - const FakeVmServiceRequest( + FakeVmServiceRequest( method: 'ext.flutter.debugDumpRenderTree', args: { 'isolateId': '1', }, - error: FakeRPCError(code: RPCErrorCodes.kMethodNotFound), + error: FakeRPCError(code: vm_service.RPCErrorKind.kMethodNotFound.code), ), ] ); @@ -339,12 +339,12 @@ void main() { testWithoutContext('flutterDebugDumpApp handles missing method', () async { final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( requests: [ - const FakeVmServiceRequest( + FakeVmServiceRequest( method: 'ext.flutter.debugDumpApp', args: { 'isolateId': '1', }, - error: FakeRPCError(code: RPCErrorCodes.kMethodNotFound), + error: FakeRPCError(code: vm_service.RPCErrorKind.kMethodNotFound.code), ), ] ); @@ -358,12 +358,12 @@ void main() { testWithoutContext('flutterDebugDumpFocusTree handles missing method', () async { final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( requests: [ - const FakeVmServiceRequest( + FakeVmServiceRequest( method: 'ext.flutter.debugDumpFocusTree', args: { 'isolateId': '1', }, - error: FakeRPCError(code: RPCErrorCodes.kMethodNotFound), + error: FakeRPCError(code: vm_service.RPCErrorKind.kMethodNotFound.code), ), ] ); @@ -398,31 +398,31 @@ void main() { testWithoutContext('Framework service extension invocations return null if service disappears ', () async { final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( requests: [ - const FakeVmServiceRequest( + FakeVmServiceRequest( method: kGetSkSLsMethod, args: { 'viewId': '1234', }, - error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + error: FakeRPCError(code: vm_service.RPCErrorKind.kServiceDisappeared.code), ), - const FakeVmServiceRequest( + FakeVmServiceRequest( method: kListViewsMethod, - error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + error: FakeRPCError(code: vm_service.RPCErrorKind.kServiceDisappeared.code), ), - const FakeVmServiceRequest( + FakeVmServiceRequest( method: kScreenshotSkpMethod, - error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + error: FakeRPCError(code: vm_service.RPCErrorKind.kServiceDisappeared.code), ), - const FakeVmServiceRequest( + FakeVmServiceRequest( method: 'setVMTimelineFlags', args: { 'recordedStreams': ['test'], }, - error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + error: FakeRPCError(code: vm_service.RPCErrorKind.kServiceDisappeared.code), ), - const FakeVmServiceRequest( + FakeVmServiceRequest( method: 'getVMTimeline', - error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + error: FakeRPCError(code: vm_service.RPCErrorKind.kServiceDisappeared.code), ), ] ); @@ -450,12 +450,12 @@ void main() { testWithoutContext('getIsolateOrNull returns null if service disappears ', () async { final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( requests: [ - const FakeVmServiceRequest( + FakeVmServiceRequest( method: 'getIsolate', args: { 'isolateId': 'isolate/123', }, - error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + error: FakeRPCError(code: vm_service.RPCErrorKind.kServiceDisappeared.code), ), ] ); @@ -615,12 +615,12 @@ void main() { ], }, ), - const FakeVmServiceRequest( + FakeVmServiceRequest( method: 'getIsolate', args: { 'isolateId': '1', }, - error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + error: FakeRPCError(code: vm_service.RPCErrorKind.kServiceDisappeared.code), ), // Assume a different isolate returns. FakeVmServiceStreamResponse( @@ -700,9 +700,9 @@ void main() { 'streamId': 'Isolate', }, ), - const FakeVmServiceRequest( + FakeVmServiceRequest( method: kListViewsMethod, - error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + error: FakeRPCError(code: vm_service.RPCErrorKind.kServiceDisappeared.code), ), ]); From 4152ca43c274dd495cc00e088c17551ae28ed5d3 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Mon, 11 Nov 2024 11:45:30 -0500 Subject: [PATCH 021/386] Roll Flutter Engine from e9a44820f302 to 3cb6f4de89b6 (3 revisions) (#158456) https://github.com/flutter/engine/compare/e9a44820f302...3cb6f4de89b6 2024-11-11 mdebbar@google.com [web] Bump Firefox version to 132.0 (flutter/engine#56435) 2024-11-11 skia-flutter-autoroll@skia.org Roll Dart SDK from cde0e0dc084a to 4ea43aa234a4 (1 revision) (flutter/engine#56502) 2024-11-11 skia-flutter-autoroll@skia.org Roll Skia from 676b3b1a41be to 261316c10484 (1 revision) (flutter/engine#56503) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jsimmons@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 700fee7f31f..7614c7c90dc 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -e9a44820f3021dbac75f0a6360882a716b11544e +3cb6f4de89b6f249d89479e23ffc8ec23a8218a3 From 14e0e580b4489094e3e788acfab91174d5aa0a38 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Mon, 11 Nov 2024 13:44:16 -0500 Subject: [PATCH 022/386] Roll Packages from bb5a25815cae to 72356fda4684 (8 revisions) (#158378) https://github.com/flutter/packages/compare/bb5a25815cae...72356fda4684 2024-11-08 stuartmorgan@google.com [various] Update example app minSdkVersions (flutter/packages#8035) 2024-11-07 32538273+ValentinVignal@users.noreply.github.com [go_router] Activate leak testing (flutter/packages#7546) 2024-11-07 louisehsu@google.com [in_app_purchase_storekit] Add restore purchases and receipts (flutter/packages#7964) 2024-11-07 10687576+bparrishMines@users.noreply.github.com [interactive_media_ads] Adds remaining methods for internal wrapper of the Android native `BaseManager` (flutter/packages#7943) 2024-11-07 58529443+srujzs@users.noreply.github.com [google_sign_in/google_identity_services] Clear-up documentation of callbacks in various APIs and uses of those APIs (flutter/packages#8029) 2024-11-07 alex@mariuti.com [flutter_svg] wasm compatibility (flutter/packages#8014) 2024-11-06 jessiewong401@gmail.com Applied Gradle Plugins Declaratively for Multiple Plugin Example Apps (Part 2) (flutter/packages#8019) 2024-11-06 engine-flutter-autoroll@skia.org Roll Flutter from 29d40f7f6826 to 73546b3b71a7 (20 revisions) (flutter/packages#8028) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-packages-flutter-autoroll Please CC flutter-ecosystem@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/flutter_packages.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/flutter_packages.version b/bin/internal/flutter_packages.version index 6347df122d2..fb97db04736 100644 --- a/bin/internal/flutter_packages.version +++ b/bin/internal/flutter_packages.version @@ -1 +1 @@ -bb5a25815cae4125f2a5903a2b376db58cff2e66 +72356fda4684035d1a015f1ba16bc2f37d954d1e From c36ad608da8ccc0be9c4ee95df4eb594c8aa46b2 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Mon, 11 Nov 2024 14:16:23 -0500 Subject: [PATCH 023/386] Roll Flutter Engine from 3cb6f4de89b6 to 7b3eacd20eb6 (1 revision) (#158464) https://github.com/flutter/engine/compare/3cb6f4de89b6...7b3eacd20eb6 2024-11-11 robert.ancell@canonical.com Remove unused FlMockTextInputHandler (flutter/engine#56495) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jsimmons@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 7614c7c90dc..c3b5bc8c500 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -3cb6f4de89b6f249d89479e23ffc8ec23a8218a3 +7b3eacd20eb6e21b84c70e7b93b38342e9bfab42 From 68fa653e59677b615fa29738b32e046b2c0f9a98 Mon Sep 17 00:00:00 2001 From: Taha Tesser Date: Mon, 11 Nov 2024 21:48:32 +0200 Subject: [PATCH 024/386] Fix Chip draws `InkWell.hoverColor` is drawn on top of the provided background color with `hovered` state (#158454) Fixes [Setting hoverColor on ThemeData breaks Chip hover functionality](https://github.com/flutter/flutter/issues/157622) ### Description The bug is caused by `InkWell.hoverColor`. When `ThemeData.hoverColor` is provided, its drawn on top. To fix this, we can override `InkWell.hoverColor` when Chip state color is provided. ### Code sample
expand to view the code sample ```dart import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( hoverColor: const Color(0xFFFF0000), ), home: Scaffold( body: Center( child: RawChip( color: WidgetStateProperty.resolveWith((states) { if (states.contains(WidgetState.hovered)) { return const Color(0xFF00fF00); } return const Color(0xFF0000FF); }), label: const Text('RawChip'), onPressed: () {}, )), ), ); } } ```
### Before https://github.com/user-attachments/assets/f8974af6-5af3-4d7d-9dbe-65bf170d5fa3 ### After https://github.com/user-attachments/assets/89a5315c-c7bd-4456-8594-e2092e43952d --- packages/flutter/lib/src/material/chip.dart | 1 + packages/flutter/test/material/chip_test.dart | 43 +++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/packages/flutter/lib/src/material/chip.dart b/packages/flutter/lib/src/material/chip.dart index 2392098ed62..628b223667e 100644 --- a/packages/flutter/lib/src/material/chip.dart +++ b/packages/flutter/lib/src/material/chip.dart @@ -1407,6 +1407,7 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid onTapDown: canTap ? _handleTapDown : null, onTapCancel: canTap ? _handleTapCancel : null, onHover: canTap ? updateMaterialState(MaterialState.hovered) : null, + hoverColor: (widget.color ?? chipTheme.color) == null ? null : Colors.transparent, customBorder: resolvedShape, child: AnimatedBuilder( animation: Listenable.merge([selectController, enableController]), diff --git a/packages/flutter/test/material/chip_test.dart b/packages/flutter/test/material/chip_test.dart index 029b8c2221a..25d0b11a17a 100644 --- a/packages/flutter/test/material/chip_test.dart +++ b/packages/flutter/test/material/chip_test.dart @@ -6039,6 +6039,49 @@ 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)), + ); + }); } class _MaterialStateOutlinedBorder extends StadiumBorder implements MaterialStateOutlinedBorder { From 563fb0c743aa0c78a13e8b21253b4586fa7c19a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Sharma?= <737941+loic-sharma@users.noreply.github.com> Date: Mon, 11 Nov 2024 13:03:30 -0800 Subject: [PATCH 025/386] [SwiftPM] Simplify logic that determines if CocoaPods is used (#158409) This is a refactoring with no semantic changes. I will get a text exemption. Part of https://github.com/flutter/flutter/issues/151567 --- .../macos/darwin_dependency_management.dart | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) 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..c681308743d 100644 --- a/packages/flutter_tools/lib/src/macos/darwin_dependency_management.dart +++ b/packages/flutter_tools/lib/src/macos/darwin_dependency_management.dart @@ -90,11 +90,7 @@ class DarwinDependencyManagement { final bool useCocoapods; if (_project.usesSwiftPackageManager) { - useCocoapods = _usingCocoaPodsPlugin( - pluginCount: totalCount, - swiftPackageCount: swiftPackageCount, - cocoapodCount: podCount, - ); + 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. From 722c395dcb28e9b95c9a7a1a38232f80db8cdb87 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Mon, 11 Nov 2024 20:16:42 -0500 Subject: [PATCH 026/386] Roll Flutter Engine from 7b3eacd20eb6 to 35041f118744 (9 revisions) (#158485) https://github.com/flutter/engine/compare/7b3eacd20eb6...35041f118744 2024-11-11 skia-flutter-autoroll@skia.org Roll Dart SDK from a393f3ed040a to 69170fac244c (1 revision) (flutter/engine#56513) 2024-11-11 chris@bracken.jp iOS,macOS: Refactor TestMetalContext for ARC (flutter/engine#56510) 2024-11-11 jonahwilliams@google.com [Impeller] geometry changes to support line/point style. (flutter/engine#56340) 2024-11-11 skia-flutter-autoroll@skia.org Roll Skia from af6a4f9a85ee to 11046fd10394 (9 revisions) (flutter/engine#56508) 2024-11-11 jonahwilliams@google.com [Impeller] dont unnecessarily copy point data out of display list. (flutter/engine#56492) 2024-11-11 jonahwilliams@google.com [Impeller] fix line/polygon depth and GLES scissor state. (flutter/engine#56494) 2024-11-11 jason-simmons@users.noreply.github.com Do not stop flutter_tester if microtasks are still pending (flutter/engine#56432) 2024-11-11 skia-flutter-autoroll@skia.org Roll Skia from 261316c10484 to af6a4f9a85ee (5 revisions) (flutter/engine#56505) 2024-11-11 skia-flutter-autoroll@skia.org Roll Dart SDK from 4ea43aa234a4 to a393f3ed040a (1 revision) (flutter/engine#56506) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jsimmons@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index c3b5bc8c500..5e1926d1849 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -7b3eacd20eb6e21b84c70e7b93b38342e9bfab42 +35041f11874434233b98c095c591d85dd7772c5e From 9ba6e944d238fb7dd7925f84cacd2ff85de51c5a Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Mon, 11 Nov 2024 21:13:10 -0500 Subject: [PATCH 027/386] Roll Flutter Engine from 35041f118744 to a672f971c659 (1 revision) (#158487) https://github.com/flutter/engine/compare/35041f118744...a672f971c659 2024-11-11 magder@google.com Add dependabot github-actions group (flutter/engine#56468) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jsimmons@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 5e1926d1849..33a85bbfb24 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -35041f11874434233b98c095c591d85dd7772c5e +a672f971c65930f620c7542be58e15669372e16f From 3770a10180a00410737530f9779346695bfa6c5b Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Mon, 11 Nov 2024 22:16:33 -0500 Subject: [PATCH 028/386] Roll Flutter Engine from a672f971c659 to b0a4ca92c49e (2 revisions) (#158488) https://github.com/flutter/engine/compare/a672f971c659...b0a4ca92c49e 2024-11-12 robert.ancell@canonical.com Add FlPointerManager to process pointer events from GTK in a form suitable for Flutter. (flutter/engine#56443) 2024-11-12 skia-flutter-autoroll@skia.org Roll Skia from 11046fd10394 to 75230dbc93e6 (1 revision) (flutter/engine#56517) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jsimmons@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 33a85bbfb24..ddd33c348c1 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -a672f971c65930f620c7542be58e15669372e16f +b0a4ca92c49ec01dabc0a01f5ff18950d10dbd7e From 95a9b97f88a841497ea986b059c594d9321a08ce Mon Sep 17 00:00:00 2001 From: Valentin Vignal <32538273+ValentinVignal@users.noreply.github.com> Date: Tue, 12 Nov 2024 19:49:24 +0800 Subject: [PATCH 029/386] Add test for `dynamic_content_color.0.dart` (#158309) Fixes https://github.com/flutter/flutter/issues/130459 It adds a test for - `examples/api/lib/material/color_scheme/dynamic_content_color.0.dart` --- dev/bots/check_code_samples.dart | 42 +---- .../color_scheme/dynamic_content_color.0.dart | 28 +-- .../dynamic_content_color.0_test.dart | 163 ++++++++++++++++++ 3 files changed, 182 insertions(+), 51 deletions(-) create mode 100644 examples/api/test/material/color_scheme/dynamic_content_color.0_test.dart 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/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..f8f0e1644df 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,23 +9,23 @@ 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({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'), ]; @@ -48,7 +48,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 +105,7 @@ class _DynamicColorExampleState extends State { onChanged: (bool value) { setState(() { isLight = value; - _updateImage(widget.images[selectedImage]); + _updateImage(DynamicColorExample.images[selectedImage]); }); }) ], @@ -120,7 +120,7 @@ class _DynamicColorExampleState extends State { divider, _imagesRow( context, - widget.images, + DynamicColorExample.images, colorScheme, ), divider, @@ -192,7 +192,7 @@ class _DynamicColorExampleState extends State { return; } setState(() { - selectedImage = widget.images.indexOf(provider); + selectedImage = DynamicColorExample.images.indexOf(provider); currentColorScheme = newColorScheme; }); } @@ -227,7 +227,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/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..6287d5cc08a --- /dev/null +++ b/examples/api/test/material/color_scheme/dynamic_content_color.0_test.dart @@ -0,0 +1,163 @@ +// 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/material.dart'; +import 'package:flutter/services.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() { + + testWidgets('The theme colors are created dynamically from the first image', (WidgetTester tester) async { + await HttpOverrides.runZoned( + () async { + await tester.pumpWidget( + const example.DynamicColorExample(), + ); + + expect( + find.widgetWithText(AppBar, 'Content Based Dynamic Color'), + findsOne, + ); + expect(find.byType(Switch), findsOne); + expect(find.byIcon(Icons.light_mode), findsOne); + + // Loads the images. + // Using runAsync forces the streams to complete. This is needed because + // loading the fake image is a real async task. + await tester.pump(); + await tester.runAsync(() => Future.delayed(Duration.zero)); + await tester.runAsync(() => Future.delayed(Duration.zero)); + await tester.runAsync(() => Future.delayed(Duration.zero)); + await tester.runAsync(() => Future.delayed(Duration.zero)); + await tester.runAsync(() => Future.delayed(Duration.zero)); + await tester.pump(); + await tester.pump(kThemeChangeDuration); + + expect(find.byType(Image), findsExactly(6)); + + 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)); + + ThemeData themeData = Theme.of( + tester.element(find.byType(Scaffold)), + ); + + expect(themeData.colorScheme.primary, const Color(0xff575992)); + expect(themeData.colorScheme.secondary, const Color(0xff5d5c72)); + + await tester.tap(find.byType(Switch)); + await tester.pump(); + + // Loads the images. + // Using runAsync forces the streams to complete. This is needed because + // loading the fake image is a real async task. + await tester.runAsync(() => Future.delayed(Duration.zero)); + await tester.runAsync(() => Future.delayed(Duration.zero)); + await tester.pump(); + await tester.pump(kThemeChangeDuration); + + themeData = Theme.of(tester.element(find.byType(Scaffold))); + + expect(themeData.primaryColor, const Color(0xff131318)); + expect(themeData.colorScheme.secondary, const Color(0xffc6c4dd)); + }, + createHttpClient: (SecurityContext? securityContext) => _FakeClient(), + ); + }); +} + +class _FakeClient extends Fake implements HttpClient { + @override + Future getUrl(Uri url) async { + return _FakeHttpClientRequest(); + } + + @override + bool autoUncompress = true; +} + +class _FakeHttpClientRequest extends Fake implements HttpClientRequest { + @override + HttpHeaders get headers => _FakeHttpHeaders(); + + @override + Future close() async { + return _FakeHttpClientResponse(); + } +} + +class _FakeHttpHeaders extends Fake implements HttpHeaders {} + +class _FakeHttpClientResponse extends Fake implements HttpClientResponse { + @override + HttpClientResponseCompressionState get compressionState => HttpClientResponseCompressionState.notCompressed; + + @override + int get contentLength => _blueSquarePng.length; + + @override + int get statusCode => 200; + + @override + Future drain([E? futureValue]) { + return Future.value(futureValue as E); + } + + @override + StreamSubscription> listen( + void Function(List event)? onData, { + Function? onError, + void Function()? onDone, + bool? cancelOnError, + }) { + return Stream>.value(_blueSquarePng).listen( + onData, + onDone: onDone, + onError: onError, + cancelOnError: cancelOnError, + ); + } +} + +/// A 50x50 blue square png. +final Uint8List _blueSquarePng = Uint8List.fromList(const [ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, + 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x32, 0x08, 0x06, + 0x00, 0x00, 0x00, 0x1e, 0x3f, 0x88, 0xb1, 0x00, 0x00, 0x00, 0x48, 0x49, 0x44, + 0x41, 0x54, 0x78, 0xda, 0xed, 0xcf, 0x31, 0x0d, 0x00, 0x30, 0x08, 0x00, 0xb0, + 0x61, 0x63, 0x2f, 0xfe, 0x2d, 0x61, 0x05, 0x34, 0xf0, 0x92, 0xd6, 0x41, 0x23, + 0x7f, 0xf5, 0x3b, 0x20, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, + 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, + 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, + 0x44, 0x44, 0x44, 0x36, 0x06, 0x03, 0x6e, 0x69, 0x47, 0x12, 0x8e, 0xea, 0xaa, + 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, +]); From 423aa2ac7476120ad522a577bda1dae77ffa3ff4 Mon Sep 17 00:00:00 2001 From: "auto-submit[bot]" <98614782+auto-submit[bot]@users.noreply.github.com> Date: Tue, 12 Nov 2024 16:05:17 +0000 Subject: [PATCH 030/386] Reverts "Add test for `dynamic_content_color.0.dart` (#158309)" (#158511) Reverts: flutter/flutter#158309 Initiated by: bleroux Reason for reverting: added test is failing on CI Original PR Author: ValentinVignal Reviewed By: {bleroux} This change reverts the following previous change: Fixes https://github.com/flutter/flutter/issues/130459 It adds a test for - `examples/api/lib/material/color_scheme/dynamic_content_color.0.dart` --- dev/bots/check_code_samples.dart | 42 ++++- .../color_scheme/dynamic_content_color.0.dart | 28 +-- .../dynamic_content_color.0_test.dart | 163 ------------------ 3 files changed, 51 insertions(+), 182 deletions(-) delete mode 100644 examples/api/test/material/color_scheme/dynamic_content_color.0_test.dart diff --git a/dev/bots/check_code_samples.dart b/dev/bots/check_code_samples.dart index ae2cbe91740..f365dc22ba2 100644 --- a/dev/bots/check_code_samples.dart +++ b/dev/bots/check_code_samples.dart @@ -142,18 +142,29 @@ 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. - final List missingTests = checkForMissingTests(exampleFilenames); + // 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); // 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 && malformedLinks.isEmpty) { + if (missingFilenames.isEmpty && missingTests.isEmpty && noLongerMissing.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) { @@ -268,14 +279,35 @@ class SampleChecker { return '${path.join(testPath, path.basenameWithoutExtension(example.path))}_test.dart'; } - List checkForMissingTests(List exampleFilenames) { + (List, 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); } } - return missingTests; + // 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); } } + +// 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/examples/api/lib/material/color_scheme/dynamic_content_color.0.dart b/examples/api/lib/material/color_scheme/dynamic_content_color.0.dart index f8f0e1644df..2dde166abaf 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,23 +9,23 @@ import 'package:flutter/material.dart'; const Widget divider = SizedBox(height: 10); const double narrowScreenWidthThreshold = 400; -void main() => runApp(const DynamicColorExample()); +void main() => runApp(DynamicColorExample()); class DynamicColorExample extends StatefulWidget { - const DynamicColorExample({super.key}); + DynamicColorExample({super.key}); - static const List images = [ - NetworkImage( + final List images = [ + const NetworkImage( 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_1.png'), - NetworkImage( + const NetworkImage( 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_2.png'), - NetworkImage( + const NetworkImage( 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_3.png'), - NetworkImage( + const NetworkImage( 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_4.png'), - NetworkImage( + const NetworkImage( 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_5.png'), - NetworkImage( + const NetworkImage( 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_6.png'), ]; @@ -48,7 +48,7 @@ class _DynamicColorExampleState extends State { isLoading = true; currentColorScheme = const ColorScheme.light(); WidgetsBinding.instance.addPostFrameCallback((_) { - _updateImage(DynamicColorExample.images[selectedImage]); + _updateImage(widget.images[selectedImage]); isLoading = false; }); } @@ -105,7 +105,7 @@ class _DynamicColorExampleState extends State { onChanged: (bool value) { setState(() { isLight = value; - _updateImage(DynamicColorExample.images[selectedImage]); + _updateImage(widget.images[selectedImage]); }); }) ], @@ -120,7 +120,7 @@ class _DynamicColorExampleState extends State { divider, _imagesRow( context, - DynamicColorExample.images, + widget.images, colorScheme, ), divider, @@ -192,7 +192,7 @@ class _DynamicColorExampleState extends State { return; } setState(() { - selectedImage = DynamicColorExample.images.indexOf(provider); + selectedImage = widget.images.indexOf(provider); currentColorScheme = newColorScheme; }); } @@ -227,7 +227,7 @@ class _DynamicColorExampleState extends State { child: GestureDetector( onTap: () => _updateImage(image), child: Card( - color: DynamicColorExample.images.indexOf(image) == selectedImage + color: widget.images.indexOf(image) == selectedImage ? colorScheme.primaryContainer : colorScheme.surface, child: Padding( 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 deleted file mode 100644 index 6287d5cc08a..00000000000 --- a/examples/api/test/material/color_scheme/dynamic_content_color.0_test.dart +++ /dev/null @@ -1,163 +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 'dart:async'; -import 'dart:io'; - -import 'package:flutter/material.dart'; -import 'package:flutter/services.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() { - - testWidgets('The theme colors are created dynamically from the first image', (WidgetTester tester) async { - await HttpOverrides.runZoned( - () async { - await tester.pumpWidget( - const example.DynamicColorExample(), - ); - - expect( - find.widgetWithText(AppBar, 'Content Based Dynamic Color'), - findsOne, - ); - expect(find.byType(Switch), findsOne); - expect(find.byIcon(Icons.light_mode), findsOne); - - // Loads the images. - // Using runAsync forces the streams to complete. This is needed because - // loading the fake image is a real async task. - await tester.pump(); - await tester.runAsync(() => Future.delayed(Duration.zero)); - await tester.runAsync(() => Future.delayed(Duration.zero)); - await tester.runAsync(() => Future.delayed(Duration.zero)); - await tester.runAsync(() => Future.delayed(Duration.zero)); - await tester.runAsync(() => Future.delayed(Duration.zero)); - await tester.pump(); - await tester.pump(kThemeChangeDuration); - - expect(find.byType(Image), findsExactly(6)); - - 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)); - - ThemeData themeData = Theme.of( - tester.element(find.byType(Scaffold)), - ); - - expect(themeData.colorScheme.primary, const Color(0xff575992)); - expect(themeData.colorScheme.secondary, const Color(0xff5d5c72)); - - await tester.tap(find.byType(Switch)); - await tester.pump(); - - // Loads the images. - // Using runAsync forces the streams to complete. This is needed because - // loading the fake image is a real async task. - await tester.runAsync(() => Future.delayed(Duration.zero)); - await tester.runAsync(() => Future.delayed(Duration.zero)); - await tester.pump(); - await tester.pump(kThemeChangeDuration); - - themeData = Theme.of(tester.element(find.byType(Scaffold))); - - expect(themeData.primaryColor, const Color(0xff131318)); - expect(themeData.colorScheme.secondary, const Color(0xffc6c4dd)); - }, - createHttpClient: (SecurityContext? securityContext) => _FakeClient(), - ); - }); -} - -class _FakeClient extends Fake implements HttpClient { - @override - Future getUrl(Uri url) async { - return _FakeHttpClientRequest(); - } - - @override - bool autoUncompress = true; -} - -class _FakeHttpClientRequest extends Fake implements HttpClientRequest { - @override - HttpHeaders get headers => _FakeHttpHeaders(); - - @override - Future close() async { - return _FakeHttpClientResponse(); - } -} - -class _FakeHttpHeaders extends Fake implements HttpHeaders {} - -class _FakeHttpClientResponse extends Fake implements HttpClientResponse { - @override - HttpClientResponseCompressionState get compressionState => HttpClientResponseCompressionState.notCompressed; - - @override - int get contentLength => _blueSquarePng.length; - - @override - int get statusCode => 200; - - @override - Future drain([E? futureValue]) { - return Future.value(futureValue as E); - } - - @override - StreamSubscription> listen( - void Function(List event)? onData, { - Function? onError, - void Function()? onDone, - bool? cancelOnError, - }) { - return Stream>.value(_blueSquarePng).listen( - onData, - onDone: onDone, - onError: onError, - cancelOnError: cancelOnError, - ); - } -} - -/// A 50x50 blue square png. -final Uint8List _blueSquarePng = Uint8List.fromList(const [ - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, - 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x32, 0x08, 0x06, - 0x00, 0x00, 0x00, 0x1e, 0x3f, 0x88, 0xb1, 0x00, 0x00, 0x00, 0x48, 0x49, 0x44, - 0x41, 0x54, 0x78, 0xda, 0xed, 0xcf, 0x31, 0x0d, 0x00, 0x30, 0x08, 0x00, 0xb0, - 0x61, 0x63, 0x2f, 0xfe, 0x2d, 0x61, 0x05, 0x34, 0xf0, 0x92, 0xd6, 0x41, 0x23, - 0x7f, 0xf5, 0x3b, 0x20, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, - 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, - 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, - 0x44, 0x44, 0x44, 0x36, 0x06, 0x03, 0x6e, 0x69, 0x47, 0x12, 0x8e, 0xea, 0xaa, - 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, -]); From 148be5f894aa64d7c4e8318100b5db5ae3c9b823 Mon Sep 17 00:00:00 2001 From: Taha Tesser Date: Tue, 12 Nov 2024 18:33:51 +0200 Subject: [PATCH 031/386] Fix `NavigationBar` label style customization on the widget level (#158510) Fixes [`NavigationBar` only allows `labelTextStyle` from `NavigationBarTheme` ](https://github.com/flutter/flutter/issues/158508) ### Code sample
expand to view the code sample ```dart import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { 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)); return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( navigationBarTheme: NavigationBarThemeData( labelTextStyle: WidgetStatePropertyAll( TextStyle( fontSize: 14, fontWeight: FontWeight.bold, color: Theme.of(context).colorScheme.primary, ), ), )), home: Scaffold( appBar: AppBar( title: const Text('NavigationBar Sample'), ), body: Center( child: Padding( padding: const EdgeInsets.all(16.0), child: Text( "NavigationBar labels are customized using NavigationBar.labelTextStyle", style: Theme.of(context).textTheme.headlineSmall, textAlign: TextAlign.center, ), ), ), bottomNavigationBar: NavigationBar( labelTextStyle: const WidgetStateProperty.fromMap( { WidgetState.disabled: disabledTextStyle, WidgetState.selected: selectedTextStyle, WidgetState.any: unselectedTextStyle, }, ), onDestinationSelected: null, destinations: const [ NavigationDestination( icon: Icon(Icons.home), label: 'Home', ), NavigationDestination( icon: Icon(Icons.favorite_rounded), label: 'Favorites', ), NavigationDestination( enabled: false, icon: Icon(Icons.settings), label: 'Settings', ), ], ), ), ); } } ```
### Preview Screenshot 2024-11-12 at 17 18 00 --- .../lib/src/material/navigation_bar.dart | 28 +++++- .../test/material/navigation_bar_test.dart | 95 +++++++++++++++++-- 2 files changed, 113 insertions(+), 10 deletions(-) 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/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!; +} From 19411b638b2e0bb6d3eab9e13269a4ed80361584 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Tue, 12 Nov 2024 11:36:54 -0500 Subject: [PATCH 032/386] Roll Flutter Engine from b0a4ca92c49e to 877abb9ad6ff (2 revisions) (#158506) https://github.com/flutter/engine/compare/b0a4ca92c49e...877abb9ad6ff 2024-11-12 skia-flutter-autoroll@skia.org Roll Skia from 75230dbc93e6 to aa099ff91e2f (3 revisions) (flutter/engine#56525) 2024-11-12 chinmaygarde@google.com [Impeller] Add OpenGL debugging utilities. (flutter/engine#56515) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index ddd33c348c1..60cb1107a31 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -b0a4ca92c49ec01dabc0a01f5ff18950d10dbd7e +877abb9ad6ff9bc35a8b5056e3106bf544103d02 From 9a2e249025ea98e4374bdbfbdac818f2f05f98b5 Mon Sep 17 00:00:00 2001 From: Jiten Patel Date: Tue, 12 Nov 2024 23:29:48 +0530 Subject: [PATCH 033/386] Made Cupertino dialog more like a native dialog in dark mode (#157218) This PR addresses an issue where the `CupertinoAlertDialog` was not fully visible in dark mode. The dialog now adapts better to dark mode themes, ensuring proper contrast and readability across different UI elements. Fixes: #80921 --- packages/flutter/lib/src/cupertino/colors.dart | 2 +- packages/flutter/lib/src/cupertino/dialog.dart | 4 ++-- packages/flutter/test/cupertino/dialog_test.dart | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) 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..38151897c9c 100644 --- a/packages/flutter/lib/src/cupertino/dialog.dart +++ b/packages/flutter/lib/src/cupertino/dialog.dart @@ -115,7 +115,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 +123,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 diff --git a/packages/flutter/test/cupertino/dialog_test.dart b/packages/flutter/test/cupertino/dialog_test.dart index 5123fc5281a..8476e0bdf20 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)), ); }); From 37d80ce25f68682041b067db77229e0ee93d4e71 Mon Sep 17 00:00:00 2001 From: Andrew Kolos Date: Tue, 12 Nov 2024 10:14:45 -0800 Subject: [PATCH 034/386] add filesystem error handling to `systemTempDirectory` (#158481) Fixes https://github.com/flutter/flutter/issues/153777. To summarize that issue, `ErrorHandlingFileSystem.systemTempDirectory` calls [`LocalFileSystem.systemTempDirectory`](https://github.com/flutter/flutter/blob/45c8881eb289e3b68e890cefa0acd13dbf800147/packages/flutter_tools/lib/src/base/file_system.dart#L229), which makes a `Directory.createSync` call, which can throw exceptions that _should_ be handled and result in a graceful tool exit (e.g. insufficient storage). However, we aren't catching those, hence this issue. All we need to do is wrap that call with the `FileSystemException`-handling logic we already have in the tool. See the diff. I don't think I'll be cherry-picking this since 1) it's not an extremely common crash and 2) users can probably pick apart the crash message and figure out that they need to clear some storage space to proceed.
Pre-launch checklist
--- .../lib/src/base/error_handling_io.dart | 2 +- .../base/error_handling_io_test.dart | 31 ++++++++++++++++++- 2 files changed, 31 insertions(+), 2 deletions(-) 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..e7086141d92 100644 --- a/packages/flutter_tools/lib/src/base/error_handling_io.dart +++ b/packages/flutter_tools/lib/src/base/error_handling_io.dart @@ -124,7 +124,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/test/general.shard/base/error_handling_io_test.dart b/packages/flutter_tools/test/general.shard/base/error_handling_io_test.dart index a43367c3419..c4b661dfaa6 100644 --- a/packages/flutter_tools/test/general.shard/base/error_handling_io_test.dart +++ b/packages/flutter_tools/test/general.shard/base/error_handling_io_test.dart @@ -884,7 +884,7 @@ void main() { }); }); - testWithoutContext("ErrorHandlingFileSystem.systemTempDirectory wraps delegates filesystem's systemTempDirectory", () { + testWithoutContext("ErrorHandlingFileSystem.systemTempDirectory wraps delegate filesystem's systemTempDirectory", () { final FileExceptionHandler exceptionHandler = FileExceptionHandler(); final MemoryFileSystem delegate = MemoryFileSystem.test( @@ -921,6 +921,35 @@ Please ensure that the SDK and/or project is installed in a location that has re ); }); + testWithoutContext("ErrorHandlingFileSystem.systemTempDirectory handles any exception thrown by the delegate's systemTempDirectory implementation", () { + final FileExceptionHandler exceptionHandler = FileExceptionHandler(); + exceptionHandler.addTempError( + FileSystemOp.create, + const FileSystemException( + 'Creation of temporary directory failed', + 'some/temp/path', + OSError( + 'No space left on device', + 28, + ), + ), + ); + + final MemoryFileSystem delegate = MemoryFileSystem.test( + opHandle: exceptionHandler.opHandle, + ); + + final FileSystem fs = ErrorHandlingFileSystem( + delegate: delegate, + platform: FakePlatform(), + ); + + expect( + () => fs.systemTempDirectory, + throwsToolExit(message: 'Free up space and try again.'), + ); + }); + group('ProcessManager on windows throws tool exit', () { const int kDeviceFull = 112; const int kUserMappedSectionOpened = 1224; From 003135e2d0e09f5986e601d116fa16f08a9abcf6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Sharma?= <737941+loic-sharma@users.noreply.github.com> Date: Tue, 12 Nov 2024 12:01:26 -0800 Subject: [PATCH 035/386] [SwiftPM] Update .flutter-plugin-dependencies format (#158138) In the future, it will be possible for Swift Package Manager to be enabled on one but not all platforms (see https://github.com/flutter/flutter/issues/151567#issuecomment-2455941279). This updates the `.flutter-plugin-dependencies` file format to separate iOS's and macOS's SwiftPM enablement. For now, these platforms will always have the same value. This `.flutter-plugin-dependencies` file is read by our CocoaPods scripts to determine whether we should use CocoaPods or not to inject plugins. Part of https://github.com/flutter/flutter/issues/151567 --- .../bin/tasks/plugin_dependencies_test.dart | 14 +++++++++- packages/flutter_tools/bin/podhelper.rb | 8 ++++-- .../lib/src/flutter_plugins.dart | 13 +++++++-- .../test/general.shard/plugins_test.dart | 28 +++++++++++++++++-- .../swift_package_manager_test.dart | 18 ++++++------ 5 files changed, 63 insertions(+), 18 deletions(-) diff --git a/dev/devicelab/bin/tasks/plugin_dependencies_test.dart b/dev/devicelab/bin/tasks/plugin_dependencies_test.dart index baae2f6bf63..e0f6178c9f0 100644 --- a/dev/devicelab/bin/tasks/plugin_dependencies_test.dart +++ b/dev/devicelab/bin/tasks/plugin_dependencies_test.dart @@ -210,7 +210,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 +304,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/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/lib/src/flutter_plugins.dart b/packages/flutter_tools/lib/src/flutter_plugins.dart index f19d2450f1a..e815d750620 100644 --- a/packages/flutter_tools/lib/src/flutter_plugins.dart +++ b/packages/flutter_tools/lib/src/flutter_plugins.dart @@ -214,7 +214,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 +251,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. @@ -1065,10 +1070,12 @@ Future refreshPluginsList( // Write the legacy plugin files to avoid breaking existing apps. final bool legacyChanged = useImplicitPubspecResolution && _writeFlutterPluginsListLegacy(project, plugins); + final bool swiftPackageManagerEnabled = !forceCocoaPodsOnly && project.usesSwiftPackageManager; final bool changed = _writeFlutterPluginsList( project, plugins, - forceCocoaPodsOnly: forceCocoaPodsOnly, + swiftPackageManagerEnabledIos: swiftPackageManagerEnabled, + swiftPackageManagerEnabledMacos: swiftPackageManagerEnabled, ); if (changed || legacyChanged || forceCocoaPodsOnly) { createPluginSymlinks(project, force: true); diff --git a/packages/flutter_tools/test/general.shard/plugins_test.dart b/packages/flutter_tools/test/general.shard/plugins_test.dart index cc3a29ddd60..6051e967bd8 100644 --- a/packages/flutter_tools/test/general.shard/plugins_test.dart +++ b/packages/flutter_tools/test/general.shard/plugins_test.dart @@ -548,7 +548,15 @@ dependencies: expect(jsonContent['dependencyGraph'], expectedDependencyGraph); expect(jsonContent['date_created'], dateCreated.toString()); expect(jsonContent['version'], '1.0.0'); - expect(jsonContent['swift_package_manager_enabled'], false); + + final Map expectedSwiftPackageManagerEnabled = { + 'ios': false, + 'macos': false, + }; + expect( + jsonContent['swift_package_manager_enabled'], + expectedSwiftPackageManagerEnabled, + ); // Make sure tests are updated if a new object is added/removed. final List expectedKeys = [ @@ -665,7 +673,14 @@ dependencies: .readAsStringSync(); final Map jsonContent = json.decode(pluginsString) as Map; - expect(jsonContent['swift_package_manager_enabled'], true); + final Map expectedSwiftPackageManagerEnabled = { + 'ios': true, + 'macos': true, + }; + expect( + jsonContent['swift_package_manager_enabled'], + expectedSwiftPackageManagerEnabled, + ); }, overrides: { FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), @@ -702,7 +717,14 @@ dependencies: .readAsStringSync(); final Map jsonContent = json.decode(pluginsString) as Map; - expect(jsonContent['swift_package_manager_enabled'], false); + final Map expectedSwiftPackageManagerEnabled = { + 'ios': false, + 'macos': false, + }; + expect( + jsonContent['swift_package_manager_enabled'], + expectedSwiftPackageManagerEnabled, + ); }, overrides: { FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), diff --git a/packages/flutter_tools/test/integration.shard/swift_package_manager_test.dart b/packages/flutter_tools/test/integration.shard/swift_package_manager_test.dart index a07ed3e64f3..dcc7f09df16 100644 --- a/packages/flutter_tools/test/integration.shard/swift_package_manager_test.dart +++ b/packages/flutter_tools/test/integration.shard/swift_package_manager_test.dart @@ -2,6 +2,8 @@ // 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:file_testing/file_testing.dart'; import 'package:flutter_tools/src/base/error_handling_io.dart'; import 'package:flutter_tools/src/base/file_system.dart'; @@ -553,14 +555,14 @@ void main() { .childFile('.flutter-plugins-dependencies'); expect(flutterPluginsDependenciesFile, exists); - expect( - flutterPluginsDependenciesFile.readAsStringSync(), - isNot(contains('"swift_package_manager_enabled":true')), - ); - expect( - flutterPluginsDependenciesFile.readAsStringSync(), - contains('"swift_package_manager_enabled":false'), - ); + + final String dependenciesString = flutterPluginsDependenciesFile.readAsStringSync(); + final Map? dependenciesJson = json.decode(dependenciesString) as Map?; + final Map? swiftPackageManagerEnabled = + dependenciesJson?['swift_package_manager_enabled'] as Map?; + final bool? swiftPackageManagerEnabledIos = swiftPackageManagerEnabled?['ios'] as bool?; + + expect(swiftPackageManagerEnabledIos, isFalse); }, skip: !platform.isMacOS); // [intended] Swift Package Manager only works on macos. test("Generated Swift package uses iOS's project minimum deployment", () async { From 9992e9bc5c5c294b9c0f7710c7656bb34d3297c5 Mon Sep 17 00:00:00 2001 From: Hannah Jin Date: Tue, 12 Nov 2024 12:19:46 -0800 Subject: [PATCH 036/386] Support materialTapTargetSize in PopupMenuButton (#158357) fix https://github.com/flutter/flutter/issues/128697 PopupMenuButton can take customized child, in that case if ` widgt.style.tapTargetSize` is set to `padded`, PopupMenuButton should support it. if child is null, default child is an iconButton, which is already 48x48. ## Pre-launch Checklist - [ ] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [ ] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [ ] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [ ] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [ ] I updated/added relevant documentation (doc comments with `///`). - [ ] I added new tests to check the change I am making, or this PR is [test-exempt]. - [ ] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [ ] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- .../flutter/lib/src/material/popup_menu.dart | 14 +++++++- .../test/material/popup_menu_test.dart | 35 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/packages/flutter/lib/src/material/popup_menu.dart b/packages/flutter/lib/src/material/popup_menu.dart index ebbe302d716..fc13494539a 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: @@ -1554,7 +1555,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 +1566,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/test/material/popup_menu_test.dart b/packages/flutter/test/material/popup_menu_test.dart index 3a1a76d5469..a6a56c55778 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); From 8e5bd5af869f11285f9d7fc583c12ee03cf356e3 Mon Sep 17 00:00:00 2001 From: Christopher Fujino Date: Tue, 12 Nov 2024 13:22:56 -0800 Subject: [PATCH 037/386] force Linux plugin_test to run on Ubuntu 20.04 (#158529) Work around propagation from https://github.com/flutter/flutter/issues/158521 --- .ci.yaml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.ci.yaml b/.ci.yaml index 1f681011e38..da9363eecd4 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -1040,6 +1040,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 From 638331b13328245d7fd5b8cffd729622e3518b8b Mon Sep 17 00:00:00 2001 From: Reid Baker Date: Tue, 12 Nov 2024 16:07:55 -0600 Subject: [PATCH 038/386] Update test to include more complete instructions for how to run tests locally, add example to andoid 11 tests as well (#158528) Follow @matanlurey's example and include how to run a test at the top of the test file. --- .../run_android_java11_integration_tool_tests.dart | 14 ++++++++++++++ .../run_flutter_driver_android_tests.dart | 6 ++++-- 2 files changed, 18 insertions(+), 2 deletions(-) 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 e2f97f6e150..7b892e7acc4 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...'); From ee586d45ad73633cdc02d08322a9445b2c1da917 Mon Sep 17 00:00:00 2001 From: Jenn Magder Date: Tue, 12 Nov 2024 16:38:16 -0800 Subject: [PATCH 039/386] Clean up dependabot config, add github-action group (#158408) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Delete bundler and docker, these directories no longer exist and we have no Docker or Gemfiles any more. 2. Update outdated reviewer list which was blocking any reviewers from being added. https://github.com/flutter/flutter/pull/157473#issuecomment-2433542624 3. Change github action update from daily to weekly 4. Add a `group` so all github action dependencies are updated in the same PR, instead of one-per-dependency. The PR will look like: __________ Screenshot 2024-11-08 at 11 08 52 AM __________ See also https://github.com/flutter/packages/pull/8044 --- .github/dependabot.yml | 30 ++++-------------------------- 1 file changed, 4 insertions(+), 26 deletions(-) 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" From 72fc9b4b378b062b1e953b186cef578bd3951ac3 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Tue, 12 Nov 2024 16:42:00 -0800 Subject: [PATCH 040/386] Explain how to use `flutter channel`. (#158533) Closes https://github.com/flutter/flutter/issues/152274. I ran into https://github.com/flutter/flutter/issues/152274 myself, so seemed like an easy fix. --- .../lib/src/commands/channel.dart | 14 +++++++--- .../test/general.shard/channel_test.dart | 26 +++++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) 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/test/general.shard/channel_test.dart b/packages/flutter_tools/test/general.shard/channel_test.dart index d973a2e180b..c235a6b3a90 100644 --- a/packages/flutter_tools/test/general.shard/channel_test.dart +++ b/packages/flutter_tools/test/general.shard/channel_test.dart @@ -54,6 +54,32 @@ void main() { ); } + testUsingContext('usage (--help) explains how to use channel', () async { + final ChannelCommand command = ChannelCommand(); + + // Required because otherwise command.usage fails as it is not hooked up. + createTestCommandRunner(command); + + // TODO(matanlurey): https://github.com/flutter/flutter/issues/158532 + // + // .usage is checked instead of log output because by default + // every command emits usage directly to stdout (via print) instead of + // to the interfaces provided. It would be a much larger refactor to + // change how every command works: + expect( + command.usage, + stringContainsInOrder([ + 'List or switch Flutter channels', + 'Common commands:', + 'List Flutter channels', + "Switch to Flutter's main channel.", + ]), + ); + }, overrides: { + ProcessManager: () => FakeProcessManager.empty(), + FileSystem: () => MemoryFileSystem.test(), + }); + testUsingContext('list', () async { await simpleChannelTest(['channel']); }, overrides: { From a0f2154419ae74f5c00b359c661277a108315218 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Tue, 12 Nov 2024 17:04:01 -0800 Subject: [PATCH 041/386] Allow `devDependencies` to be omitted and not cause a tool crash. (#158518) Closes https://github.com/flutter/flutter/issues/158441. --- .../lib/src/compute_dev_dependencies.dart | 6 ++- .../compute_dev_dependencies_test.dart | 46 +++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/packages/flutter_tools/lib/src/compute_dev_dependencies.dart b/packages/flutter_tools/lib/src/compute_dev_dependencies.dart index 7c76b855c54..d55491a0399 100644 --- a/packages/flutter_tools/lib/src/compute_dev_dependencies.dart +++ b/packages/flutter_tools/lib/src/compute_dev_dependencies.dart @@ -64,6 +64,10 @@ Future> computeExclusiveDevDependencies( } 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 +119,7 @@ Future> computeExclusiveDevDependencies( // Start initially with every `devDependency` listed. final Set devDependencies = asListOrFail( - rootPackage['devDependencies'], + rootPackage['devDependencies'] ?? [], 'devDependencies', ).toSet(); diff --git a/packages/flutter_tools/test/general.shard/compute_dev_dependencies_test.dart b/packages/flutter_tools/test/general.shard/compute_dev_dependencies_test.dart index 95afae0384d..1f1f7b9638b 100644 --- a/packages/flutter_tools/test/general.shard/compute_dev_dependencies_test.dart +++ b/packages/flutter_tools/test/general.shard/compute_dev_dependencies_test.dart @@ -293,6 +293,52 @@ void main() { ); }); + test('omitted devDependencies in app package', () async { + // Simulates the following: + // + // # /my_app/pubspec.yaml + // name: my_app + // dependencies: + // package_a: + // + // # /package_a/pubspec.yaml + // name: package_a + final ProcessManager processes = _dartPubDepsReturns(''' + { + "root": "my_app", + "packages": [ + { + "name": "my_app", + "kind": "root", + "dependencies": [ + "package_a" + ], + "directDependencies": [ + "package_a" + ] + }, + { + "name": "package_a", + "kind": "direct", + "dependencies": [], + "directDependencies": [] + } + ] + }'''); + + final Set dependencies = await computeExclusiveDevDependencies( + processes, + projectPath: _fakeProjectPath, + logger: logger, + ); + + expect( + dependencies, + isEmpty, + reason: 'No devDependencies: [] specified but still parsed successfully', + ); + }); + test('throws and logs on non-zero exit code', () async { final ProcessManager processes = _dartPubDepsFails( 'Bad thing', From 90074a8b32219a9dfc0ebe55349de342947b3b56 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Tue, 12 Nov 2024 20:08:13 -0500 Subject: [PATCH 042/386] Roll Flutter Engine from 877abb9ad6ff to 08348c9eebcc (8 revisions) (#158541) https://github.com/flutter/engine/compare/877abb9ad6ff...08348c9eebcc 2024-11-12 jason-simmons@users.noreply.github.com [Linux] Configure depth and stencil framebuffer attachments needed for Impeller (flutter/engine#56516) 2024-11-12 chris@bracken.jp macOS: ARC bridge casts for FlutterMetalTexture.user_data (flutter/engine#56518) 2024-11-12 jonahwilliams@google.com [Impeller] prevent no-op backend from throwing exceptions during image decoding (flutter/engine#56522) 2024-11-12 skia-flutter-autoroll@skia.org Roll Dart SDK from 69170fac244c to 5f42ef8f15d5 (4 revisions) (flutter/engine#56539) 2024-11-12 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from BajfrJuYeyWvnBhuM... to z-cm2nR0aJ4lXfwZ0... (flutter/engine#56538) 2024-11-12 skia-flutter-autoroll@skia.org Roll Skia from aa099ff91e2f to 7d5c206fc873 (6 revisions) (flutter/engine#56541) 2024-11-12 jason-simmons@users.noreply.github.com [Impeller] In canvas_unittests, only create an MSAA offscreen texture if the platform supports MSAA (flutter/engine#56542) 2024-11-12 bruno.leroux@gmail.com [iOS] Fix slider semantics node answer to accessibility activate (flutter/engine#56427) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from BajfrJuYeyWv to z-cm2nR0aJ4l If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 60cb1107a31..d0d7485beb6 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -877abb9ad6ff9bc35a8b5056e3106bf544103d02 +08348c9eebcc4c145fe53e8e2abaf36c9b4ee5bc diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index c829a3a8c57..f378973c9b5 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -BajfrJuYeyWvnBhuMsYlPmNADNd_e4gS4bvqpD0uDTsC +z-cm2nR0aJ4lXfwZ06yE2TbodgbSvTQLHywr_um4fpMC From a6d81aa8f153f30a183ee708e97015010649b7ae Mon Sep 17 00:00:00 2001 From: Flutter GitHub Bot Date: Tue, 12 Nov 2024 21:29:25 -0500 Subject: [PATCH 043/386] Marks Mac_arm64_ios hot_mode_dev_cycle_ios__benchmark to be flaky (#158242) Issue link: https://github.com/flutter/flutter/issues/158241 --- .ci.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.ci.yaml b/.ci.yaml index da9363eecd4..a89c21cc957 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -5212,6 +5212,7 @@ targets: task_name: hot_mode_dev_cycle_ios__benchmark - name: Mac_arm64_ios hot_mode_dev_cycle_ios__benchmark + bringup: true # Flaky https://github.com/flutter/flutter/issues/158241 recipe: devicelab/devicelab_drone presubmit: false timeout: 60 From a058b3c2207d6b8573c317398df910fbdac7e52b Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Tue, 12 Nov 2024 21:35:17 -0500 Subject: [PATCH 044/386] Roll Flutter Engine from 08348c9eebcc to ef760d6e1f13 (1 revision) (#158545) https://github.com/flutter/engine/compare/08348c9eebcc...ef760d6e1f13 2024-11-13 skia-flutter-autoroll@skia.org Roll Skia from 7d5c206fc873 to 02dd72c2fbc2 (4 revisions) (flutter/engine#56547) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index d0d7485beb6..8f35e4faeac 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -08348c9eebcc4c145fe53e8e2abaf36c9b4ee5bc +ef760d6e1f13e76e87049fcf9f6882f7a330b7f1 From 4b5f6e2785636afb0c5a4d14b981c332c84727e4 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Tue, 12 Nov 2024 23:57:36 -0500 Subject: [PATCH 045/386] Roll Flutter Engine from ef760d6e1f13 to 05c14d8b4cd7 (3 revisions) (#158551) https://github.com/flutter/engine/compare/ef760d6e1f13...05c14d8b4cd7 2024-11-13 skia-flutter-autoroll@skia.org Roll Dart SDK from 5f42ef8f15d5 to c7d140d18895 (2 revisions) (flutter/engine#56552) 2024-11-13 jonahwilliams@google.com [engine] force semantics action to post a task. (flutter/engine#56514) 2024-11-13 chinmaygarde@google.com [Impeller] Wrap provided FBO instead of defaulting to FBO0 and cleanup/document the texture API. (flutter/engine#56543) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 8f35e4faeac..68766b397f1 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -ef760d6e1f13e76e87049fcf9f6882f7a330b7f1 +05c14d8b4cd763ab03c2ae90d52cae5211b9d2af From 4de32b870212f33610be0ec122001d695f373a77 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Wed, 13 Nov 2024 03:16:33 -0500 Subject: [PATCH 046/386] Roll Flutter Engine from 05c14d8b4cd7 to db3e5af2ca22 (1 revision) (#158553) https://github.com/flutter/engine/compare/05c14d8b4cd7...db3e5af2ca22 2024-11-13 skia-flutter-autoroll@skia.org Roll Skia from 02dd72c2fbc2 to ca10bc19c67e (2 revisions) (flutter/engine#56554) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 68766b397f1..d9f412749c5 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -05c14d8b4cd763ab03c2ae90d52cae5211b9d2af +db3e5af2ca2267183b71a8b68ba4ac2330e957a6 From 2d1a3efc38ac74d3dccd2d5d612e7ca5f85f2a69 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Wed, 13 Nov 2024 10:03:53 -0800 Subject: [PATCH 047/386] Move `dart pub deps` call to `.deps` and use it accordingly (#158524) Closes https://github.com/flutter/flutter/issues/158396, closes https://github.com/flutter/flutter/pull/158370. --- .../lib/src/compute_dev_dependencies.dart | 48 +---- packages/flutter_tools/lib/src/dart/pub.dart | 49 +++++ .../lib/src/flutter_plugins.dart | 5 +- .../hermetic/build_ios_test.dart | 67 +++--- .../hermetic/build_ipa_test.dart | 85 ++++---- .../hermetic/build_macos_test.dart | 36 ++-- .../compute_dev_dependencies_test.dart | 170 ++++++++-------- .../general.shard/dart/pub_deps_test.dart | 192 ++++++++++++++++++ .../test/general.shard/dart/pub_get_test.dart | 68 +++---- .../ios_device_start_nonprebuilt_test.dart | 26 ++- .../macos/cocoapod_utils_test.dart | 42 ++-- .../test/general.shard/plugins_test.dart | 5 +- packages/flutter_tools/test/src/context.dart | 2 +- .../flutter_tools/test/src/fake_pub_deps.dart | 84 ++++++++ packages/flutter_tools/test/src/testbed.dart | 2 +- .../flutter_tools/test/src/throwing_pub.dart | 56 ++--- 16 files changed, 600 insertions(+), 337 deletions(-) create mode 100644 packages/flutter_tools/test/general.shard/dart/pub_deps_test.dart create mode 100644 packages/flutter_tools/test/src/fake_pub_deps.dart diff --git a/packages/flutter_tools/lib/src/compute_dev_dependencies.dart b/packages/flutter_tools/lib/src/compute_dev_dependencies.dart index d55491a0399..a1305c53e44 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,54 +14,19 @@ 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) { diff --git a/packages/flutter_tools/lib/src/dart/pub.dart b/packages/flutter_tools/lib/src/dart/pub.dart index 656ab79109d..5e5e539c023 100644 --- a/packages/flutter_tools/lib/src/dart/pub.dart +++ b/packages/flutter_tools/lib/src/dart/pub.dart @@ -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 succcessful, 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 @@ -373,6 +380,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/flutter_plugins.dart b/packages/flutter_tools/lib/src/flutter_plugins.dart index e815d750620..471dba42f92 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'; @@ -128,9 +129,9 @@ Future> findPlugins( devDependencies = {}; } else { devDependencies = await computeExclusiveDevDependencies( - globals.processManager, + pub, logger: globals.logger, - projectPath: project.directory.path, + project: project, ); } for (final Package package in packageConfig.packages) { 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..8074c58d829 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,13 +107,6 @@ 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( @@ -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,7 +767,6 @@ STDERR STUFF }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ - dartPubDepsCommand, setUpFakeXcodeBuildHandler( 'Debug', additionalCommandArguements: [ @@ -787,6 +782,7 @@ STDERR STUFF 'LUCI_CI': 'True' } ), + Pub: FakePubWithPrimedDeps.new, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); @@ -840,7 +836,6 @@ STDERR STUFF }, overrides: { FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list([ - dartPubDepsCommand, setUpFakeXcodeBuildHandler( 'Release', additionalCommandArguements: [ @@ -856,6 +851,7 @@ STDERR STUFF 'LUCI_CI': 'True' } ), + Pub: FakePubWithPrimedDeps.new, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); } diff --git a/packages/flutter_tools/test/general.shard/compute_dev_dependencies_test.dart b/packages/flutter_tools/test/general.shard/compute_dev_dependencies_test.dart index 1f1f7b9638b..f9dec39e0bc 100644 --- a/packages/flutter_tools/test/general.shard/compute_dev_dependencies_test.dart +++ b/packages/flutter_tools/test/general.shard/compute_dev_dependencies_test.dart @@ -2,11 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:file/file.dart'; +import 'package:file/memory.dart'; import 'package:flutter_tools/src/base/logger.dart'; +import 'package:flutter_tools/src/base/platform.dart'; +import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/compute_dev_dependencies.dart'; +import 'package:flutter_tools/src/dart/pub.dart'; +import 'package:flutter_tools/src/project.dart'; +import 'package:flutter_tools/src/reporting/reporting.dart'; import '../src/common.dart'; import '../src/fake_process_manager.dart'; +import '../src/fakes.dart'; + +const String _dartBin = 'bin/cache/dart-sdk/bin/dart'; // For all of these examples, imagine the following package structure: // @@ -20,12 +30,29 @@ import '../src/fake_process_manager.dart'; // /package_c // pubspec.yaml void main() { + late FileSystem fileSystem; + late FlutterProject project; late BufferLogger logger; setUp(() { + Cache.flutterRoot = ''; + fileSystem = MemoryFileSystem.test(); + project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); logger = BufferLogger.test(); }); + Pub pub(ProcessManager processManager) { + return Pub.test( + fileSystem: fileSystem, + logger: logger, + processManager: processManager, + usage: TestUsage(), + platform: FakePlatform(), + botDetector: const FakeBotDetector(false), + stdio: FakeStdio(), + ); + } + test('no dev dependencies at all', () async { // Simulates the following: // @@ -38,7 +65,8 @@ void main() { // name: package_a // dependencies: // package_b: - final ProcessManager processes = _dartPubDepsReturns(''' + final ProcessManager processes = _dartPubDepsReturns( + ''' { "root": "my_app", "packages": [ @@ -71,11 +99,13 @@ void main() { "directDependencies": [] } ] - }'''); + }''', + project: project, + ); final Set dependencies = await computeExclusiveDevDependencies( - processes, - projectPath: _fakeProjectPath, + pub(processes), + project: project, logger: logger, ); @@ -99,7 +129,8 @@ void main() { // // # /package_a/pubspec.yaml // name: package_a - final ProcessManager processes = _dartPubDepsReturns(''' + final ProcessManager processes = _dartPubDepsReturns( + ''' { "root": "my_app", "packages": [ @@ -130,11 +161,13 @@ void main() { "directDependencies": [] } ] - }'''); + }''', + project: project, + ); final Set dependencies = await computeExclusiveDevDependencies( - processes, - projectPath: _fakeProjectPath, + pub(processes), + project: project, logger: logger, ); @@ -160,7 +193,8 @@ void main() { // name: package_a // dependencies: // package_b: - final ProcessManager processes = _dartPubDepsReturns(''' + final ProcessManager processes = _dartPubDepsReturns( + ''' { "root": "my_app", "packages": [ @@ -195,11 +229,13 @@ void main() { "directDependencies": [] } ] - }'''); + }''', + project: project, + ); final Set dependencies = await computeExclusiveDevDependencies( - processes, - projectPath: _fakeProjectPath, + pub(processes), + project: project, logger: logger, ); @@ -232,7 +268,8 @@ void main() { // // # /package_c/pubspec.yaml // name: package_c - final ProcessManager processes = _dartPubDepsReturns(''' + final ProcessManager processes = _dartPubDepsReturns( + ''' { "root": "my_app", "packages": [ @@ -278,11 +315,13 @@ void main() { "directDependencies": [] } ] - }'''); + }''', + project: project, + ); final Set dependencies = await computeExclusiveDevDependencies( - processes, - projectPath: _fakeProjectPath, + pub(processes), + project: project, logger: logger, ); @@ -293,7 +332,7 @@ void main() { ); }); - test('omitted devDependencies in app package', () async { + test('omitted devDependencies in app package', () async { // Simulates the following: // // # /my_app/pubspec.yaml @@ -324,11 +363,13 @@ void main() { "directDependencies": [] } ] - }'''); + }''', + project: project, + ); final Set dependencies = await computeExclusiveDevDependencies( - processes, - projectPath: _fakeProjectPath, + pub(processes), + project: project, logger: logger, ); @@ -339,55 +380,9 @@ void main() { ); }); - test('throws and logs on non-zero exit code', () async { - final ProcessManager processes = _dartPubDepsFails( - 'Bad thing', - exitCode: 1, - ); - - await expectLater( - computeExclusiveDevDependencies( - processes, - projectPath: _fakeProjectPath, - logger: logger, - ), - throwsA( - isA().having( - (StateError e) => e.message, - 'message', - contains('dart pub deps --json failed'), - ), - ), - ); - - expect(logger.traceText, isEmpty); - }); - - test('throws and logs on unexpected output type', () async { - final ProcessManager processes = _dartPubDepsReturns( - 'Not JSON haha!', - ); - - await expectLater( - computeExclusiveDevDependencies( - processes, - projectPath: _fakeProjectPath, - logger: logger, - ), - throwsA( - isA().having( - (StateError e) => e.message, - 'message', - contains('dart pub deps --json had unexpected output'), - ), - ), - ); - - expect(logger.traceText, contains('Not JSON haha')); - }); - test('throws and logs on invalid JSON', () async { - final ProcessManager processes = _dartPubDepsReturns(''' + final ProcessManager processes = _dartPubDepsReturns( + ''' { "root": "my_app", "packages": [ @@ -420,12 +415,14 @@ void main() { "directDependencies": [] } ] - }'''); + }''', + project: project, + ); await expectLater( computeExclusiveDevDependencies( - processes, - projectPath: _fakeProjectPath, + pub(processes), + project: project, logger: logger, ), throwsA( @@ -445,28 +442,21 @@ void main() { }); } -const String _fakeProjectPath = '/path/to/project'; - -ProcessManager _dartPubDepsReturns(String dartPubDepsOutput) { - return FakeProcessManager.list([ - FakeCommand( - command: const ['dart', 'pub', 'deps', '--json'], - stdout: dartPubDepsOutput, - workingDirectory: _fakeProjectPath, - ), - ]); -} - -ProcessManager _dartPubDepsFails( - String dartPubDepsError, { - required int exitCode, +ProcessManager _dartPubDepsReturns( + String dartPubDepsOutput, { + required FlutterProject project, }) { return FakeProcessManager.list([ FakeCommand( - command: const ['dart', 'pub', 'deps', '--json'], - exitCode: exitCode, - stderr: dartPubDepsError, - workingDirectory: _fakeProjectPath, + command: const [ + _dartBin, + 'pub', + '--suppress-analytics', + 'deps', + '--json', + ], + stdout: dartPubDepsOutput, + workingDirectory: project.directory.path, ), ]); } diff --git a/packages/flutter_tools/test/general.shard/dart/pub_deps_test.dart b/packages/flutter_tools/test/general.shard/dart/pub_deps_test.dart new file mode 100644 index 00000000000..28934732eb4 --- /dev/null +++ b/packages/flutter_tools/test/general.shard/dart/pub_deps_test.dart @@ -0,0 +1,192 @@ +// 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/logger.dart'; +import 'package:flutter_tools/src/base/platform.dart'; +import 'package:flutter_tools/src/cache.dart'; +import 'package:flutter_tools/src/dart/pub.dart'; +import 'package:flutter_tools/src/project.dart'; +import 'package:flutter_tools/src/reporting/reporting.dart'; + +import '../../src/common.dart'; +import '../../src/fake_process_manager.dart'; +import '../../src/fakes.dart'; + +const String _dartBin = 'bin/cache/dart-sdk/bin/dart'; + +void main() { + setUpAll(() { + Cache.flutterRoot = ''; + }); + + testWithoutContext('throws a tool exit if pub cannot be run', () async { + final FakeProcessManager processManager = FakeProcessManager.empty(); + final BufferLogger logger = BufferLogger.test(); + final MemoryFileSystem fileSystem = MemoryFileSystem.test(); + + processManager.excludedExecutables.add(_dartBin); + fileSystem.file('pubspec.yaml').createSync(); + + final Pub pub = Pub.test( + fileSystem: fileSystem, + logger: logger, + processManager: processManager, + usage: TestUsage(), + platform: FakePlatform(), + botDetector: const FakeBotDetector(false), + stdio: FakeStdio(), + ); + + await expectLater( + () => pub.deps( + FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + ), + throwsToolExit( + message: 'Your Flutter SDK download may be corrupt', + ), + ); + }); + + testWithoutContext('fails on non-zero exit code', () async { + final BufferLogger logger = BufferLogger.test(); + final MemoryFileSystem fileSystem = MemoryFileSystem.test(); + final ProcessManager processManager = _dartPubDepsFails( + 'Bad thing', + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + exitCode: 1, + ); + + final Pub pub = Pub.test( + fileSystem: fileSystem, + logger: logger, + processManager: processManager, + usage: TestUsage(), + platform: FakePlatform(), + botDetector: const FakeBotDetector(false), + stdio: FakeStdio(), + ); + + await expectLater( + () => pub.deps( + FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + ), + throwsA( + isA().having( + (StateError e) => e.message, + 'message', + contains('dart pub --suppress-analytics deps --json failed'), + ), + ), + ); + }); + + testWithoutContext('fails on non-parseable JSON', () async { + final BufferLogger logger = BufferLogger.test(); + final MemoryFileSystem fileSystem = MemoryFileSystem.test(); + final ProcessManager processManager = _dartPubDepsReturns( + 'Not JSON haha!', + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + ); + + final Pub pub = Pub.test( + fileSystem: fileSystem, + logger: logger, + processManager: processManager, + usage: TestUsage(), + platform: FakePlatform(), + botDetector: const FakeBotDetector(false), + stdio: FakeStdio(), + ); + + await expectLater( + () => pub.deps( + FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + ), + throwsA( + isA().having( + (StateError e) => e.message, + 'message', + contains( + 'dart pub --suppress-analytics deps --json had unexpected output', + ), + ), + ), + ); + }); + + testWithoutContext('fails on unexpected JSON type', () async { + final BufferLogger logger = BufferLogger.test(); + final MemoryFileSystem fileSystem = MemoryFileSystem.test(); + final ProcessManager processManager = _dartPubDepsReturns( + '[]', + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + ); + + final Pub pub = Pub.test( + fileSystem: fileSystem, + logger: logger, + processManager: processManager, + usage: TestUsage(), + platform: FakePlatform(), + botDetector: const FakeBotDetector(false), + stdio: FakeStdio(), + ); + + await expectLater( + () => pub.deps( + FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + ), + throwsA( + isA().having( + (StateError e) => e.message, + 'message', + contains( + 'Not a JSON object', + ), + ), + ), + ); + }); +} + +ProcessManager _dartPubDepsReturns( + String dartPubDepsOutput, { + required FlutterProject project, +}) { + return FakeProcessManager.list([ + FakeCommand( + command: const [ + _dartBin, + 'pub', + '--suppress-analytics', + 'deps', + '--json', + ], + stdout: dartPubDepsOutput, + workingDirectory: project.directory.path, + ), + ]); +} + +ProcessManager _dartPubDepsFails( + String dartPubDepsError, { + required FlutterProject project, + required int exitCode, +}) { + return FakeProcessManager.list([ + FakeCommand( + command: const [ + _dartBin, + 'pub', + '--suppress-analytics', + 'deps', + '--json' + ], + exitCode: exitCode, + stderr: dartPubDepsError, + workingDirectory: project.directory.path, + ), + ]); +} diff --git a/packages/flutter_tools/test/general.shard/dart/pub_get_test.dart b/packages/flutter_tools/test/general.shard/dart/pub_get_test.dart index 1a9e079620c..06af2a54625 100644 --- a/packages/flutter_tools/test/general.shard/dart/pub_get_test.dart +++ b/packages/flutter_tools/test/general.shard/dart/pub_get_test.dart @@ -4,7 +4,6 @@ import 'package:file/file.dart'; import 'package:file/memory.dart'; -import 'package:flutter_tools/src/base/bot_detector.dart'; import 'package:flutter_tools/src/base/common.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/io.dart' show ProcessException; @@ -39,7 +38,7 @@ void main() { processManager: processManager, usage: TestUsage(), platform: FakePlatform(), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: FakeStdio(), ); @@ -94,7 +93,7 @@ void main() { processManager: processManager, usage: TestUsage(), platform: FakePlatform(), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: FakeStdio(), ); @@ -149,7 +148,7 @@ void main() { processManager: processManager, usage: TestUsage(), platform: FakePlatform(), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: FakeStdio(), ); @@ -203,7 +202,7 @@ void main() { processManager: processManager, usage: TestUsage(), platform: FakePlatform(), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: FakeStdio(), ); @@ -236,7 +235,7 @@ void main() { processManager: processManager, usage: TestUsage(), platform: FakePlatform(), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: FakeStdio(), ); @@ -275,7 +274,7 @@ void main() { processManager: processManager, usage: TestUsage(), platform: FakePlatform(), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: FakeStdio(), ); @@ -321,7 +320,7 @@ void main() { processManager: processManager, usage: TestUsage(), platform: FakePlatform(), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: FakeStdio(), ); @@ -366,7 +365,7 @@ void main() { processManager: processManager, usage: TestUsage(), platform: FakePlatform(), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: FakeStdio(), ); @@ -414,7 +413,7 @@ void main() { processManager: processManager, usage: TestUsage(), platform: FakePlatform(), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: FakeStdio(), ); @@ -459,7 +458,7 @@ void main() { processManager: processManager, usage: TestUsage(), platform: FakePlatform(), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: FakeStdio(), ); @@ -504,7 +503,7 @@ void main() { processManager: processManager, usage: TestUsage(), platform: FakePlatform(), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: FakeStdio(), ); @@ -552,7 +551,7 @@ void main() { processManager: processManager, usage: TestUsage(), platform: FakePlatform(), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: FakeStdio(), ); @@ -597,7 +596,7 @@ void main() { fileSystem: fileSystem, logger: logger, usage: TestUsage(), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: mockStdio, processManager: processManager, ); @@ -615,8 +614,8 @@ exit code: 66 project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), context: PubContext.flutterTests, ), - throwsA(isA() - .having((ToolExit error) => error.message, 'message', contains('Failed to update packages'))), + throwsA(isA().having((ToolExit error) => error.message, + 'message', contains('Failed to update packages'))), ); expect(logger.statusText, isEmpty); expect(logger.traceText, contains(toolExitMessage)); @@ -629,11 +628,14 @@ exit code: 66 expect(processManager, hasNoRemainingExpectations); }); - testWithoutContext('pub get with failing exit code even with OutputMode == failuresOnly', () async { + testWithoutContext( + 'pub get with failing exit code even with OutputMode == failuresOnly', + () async { final BufferLogger logger = BufferLogger.test(); final FileSystem fileSystem = MemoryFileSystem.test(); - final FakeProcessManager processManager = FakeProcessManager.list([ + final FakeProcessManager processManager = + FakeProcessManager.list([ const FakeCommand( command: [ 'bin/cache/dart-sdk/bin/dart', @@ -661,7 +663,7 @@ exit code: 66 fileSystem: fileSystem, logger: logger, usage: TestUsage(), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), processManager: processManager, ); @@ -680,7 +682,8 @@ exit code: 66 expect( logger.warningText, contains('git remote set-url upstream'), - reason: 'When update-packages fails, it is often because of missing an upsteam remote.', + reason: + 'When update-packages fails, it is often because of missing an upsteam remote.', ); expect(processManager, hasNoRemainingExpectations); }); @@ -732,7 +735,7 @@ exit code: 66 fileSystem: fileSystem, logger: logger, usage: TestUsage(), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: FakeStdio(), processManager: processManager, ); @@ -793,7 +796,7 @@ exit code: 66 fileSystem: fileSystem, logger: logger, processManager: processManager, - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: mockStdio, ); @@ -844,7 +847,7 @@ exit code: 66 fileSystem: fileSystem, logger: BufferLogger.test(), processManager: processManager, - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: mockStdio, ); @@ -915,7 +918,7 @@ exit code: 66 fileSystem: fileSystem, logger: logger, processManager: processManager, - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: FakeStdio(), ); @@ -957,7 +960,7 @@ exit code: 66 logger: BufferLogger.test(), processManager: processManager, usage: TestUsage(), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: mockStdio, platform: FakePlatform( environment: const { @@ -988,7 +991,7 @@ exit code: 66 fileSystem: fileSystem, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: FakeStdio(), usage: usage, platform: FakePlatform(environment: const { @@ -1021,7 +1024,7 @@ exit code: 66 fileSystem: fileSystem, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: FakeStdio(), usage: usage, platform: FakePlatform(environment: const { @@ -1084,7 +1087,7 @@ exit code: 66 fileSystem: fileSystem, logger: BufferLogger.test(), processManager: processManager, - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: FakeStdio(), platform: FakePlatform( environment: const { @@ -1173,7 +1176,7 @@ exit code: 66 platform: FakePlatform( environment: {}, ), - botDetector: const BotDetectorAlwaysNo(), + botDetector: const FakeBotDetector(false), stdio: FakeStdio()); fileSystem.file('version').createSync(); @@ -1211,10 +1214,3 @@ exit code: 66 logger.clear(); }); } - -class BotDetectorAlwaysNo implements BotDetector { - const BotDetectorAlwaysNo(); - - @override - Future get isRunningOnBot async => false; -} diff --git a/packages/flutter_tools/test/general.shard/ios/ios_device_start_nonprebuilt_test.dart b/packages/flutter_tools/test/general.shard/ios/ios_device_start_nonprebuilt_test.dart index a6e93cfb339..7c5d1d0c349 100644 --- a/packages/flutter_tools/test/general.shard/ios/ios_device_start_nonprebuilt_test.dart +++ b/packages/flutter_tools/test/general.shard/ios/ios_device_start_nonprebuilt_test.dart @@ -15,6 +15,7 @@ import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/base/version.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/cache.dart'; +import 'package:flutter_tools/src/dart/pub.dart'; import 'package:flutter_tools/src/device.dart'; import 'package:flutter_tools/src/device_port_forwarder.dart'; import 'package:flutter_tools/src/ios/application_package.dart'; @@ -34,6 +35,7 @@ import '../../src/common.dart'; import '../../src/context.dart' hide FakeXcodeProjectInterpreter; import '../../src/fake_devices.dart'; import '../../src/fake_process_manager.dart'; +import '../../src/fake_pub_deps.dart'; import '../../src/fakes.dart'; List _xattrArgs(FlutterProject flutterProject) { @@ -74,12 +76,7 @@ const List kRunReleaseArgs = [ // label which plugins are dependency plugins. // // Ideally processPodsIfNeeded should rely on the command (removing this call). -const List kCheckDartPubDeps = [ - 'dart', - 'pub', - 'deps', - '--json', -]; +final Pub fakePubBecauseRefreshPluginsList = FakePubWithPrimedDeps(); const String kConcurrentBuildErrorMessage = ''' "/Developer/Xcode/DerivedData/foo/XCBuildData/build.db": @@ -144,7 +141,6 @@ void main() { final BuildableIOSApp buildableIOSApp = BuildableIOSApp(flutterProject.ios, 'flutter', 'My Super Awesome App'); processManager.addCommand(FakeCommand(command: _xattrArgs(flutterProject))); - processManager.addCommand(const FakeCommand(command: kCheckDartPubDeps)); processManager.addCommand(const FakeCommand(command: kRunReleaseArgs)); final LaunchResult launchResult = await iosDevice.startApp( @@ -166,6 +162,7 @@ void main() { ); }, overrides: { ProcessManager: () => processManager, + Pub: () => fakePubBecauseRefreshPluginsList, FileSystem: () => fileSystem, Logger: () => logger, OperatingSystemUtils: () => os, @@ -219,7 +216,6 @@ void main() { fileSystem.directory('build/ios/Release-iphoneos/My Super Awesome App.app').createSync(recursive: true); processManager.addCommand(FakeCommand(command: _xattrArgs(flutterProject))); - processManager.addCommand(const FakeCommand(command: kCheckDartPubDeps)); processManager.addCommand(const FakeCommand(command: kRunReleaseArgs)); processManager.addCommand(const FakeCommand(command: [ 'rsync', @@ -258,6 +254,7 @@ void main() { expect(processManager, hasNoRemainingExpectations); }, overrides: { ProcessManager: () => processManager, + Pub: () => fakePubBecauseRefreshPluginsList, FileSystem: () => fileSystem, Logger: () => logger, OperatingSystemUtils: () => os, @@ -280,7 +277,6 @@ void main() { fileSystem.directory('build/ios/Release-iphoneos/My Super Awesome App.app').createSync(recursive: true); processManager.addCommand(FakeCommand(command: _xattrArgs(flutterProject))); - processManager.addCommand(const FakeCommand(command: kCheckDartPubDeps)); processManager.addCommand(const FakeCommand(command: [ 'xcrun', 'xcodebuild', @@ -347,6 +343,7 @@ void main() { OperatingSystemUtils: () => FakeOperatingSystemUtils( hostPlatform: HostPlatform.darwin_x64, ), + Pub: () => fakePubBecauseRefreshPluginsList, Platform: () => macPlatform, XcodeProjectInterpreter: () => fakeXcodeProjectInterpreter, Xcode: () => xcode, @@ -364,7 +361,6 @@ void main() { final BuildableIOSApp buildableIOSApp = BuildableIOSApp(flutterProject.ios, 'flutter', 'My Super Awesome App'); processManager.addCommand(FakeCommand(command: _xattrArgs(flutterProject))); - processManager.addCommand(const FakeCommand(command: kCheckDartPubDeps)); // The first xcrun call should fail with a // concurrent build exception. processManager.addCommand( @@ -419,6 +415,7 @@ void main() { hostPlatform: HostPlatform.darwin_arm64, ), Platform: () => macPlatform, + Pub: () => fakePubBecauseRefreshPluginsList, XcodeProjectInterpreter: () => fakeXcodeProjectInterpreter, Xcode: () => xcode, }); @@ -472,6 +469,7 @@ void main() { expect(processManager, hasNoRemainingExpectations); }, overrides: { ProcessManager: () => FakeProcessManager.any(), + Pub: () => fakePubBecauseRefreshPluginsList, FileSystem: () => fileSystem, Logger: () => logger, OperatingSystemUtils: () => os, @@ -507,6 +505,7 @@ void main() { expect(processManager, hasNoRemainingExpectations); }, overrides: { ProcessManager: () => FakeProcessManager.any(), + Pub: () => fakePubBecauseRefreshPluginsList, FileSystem: () => fileSystem, Logger: () => logger, OperatingSystemUtils: () => os, @@ -542,6 +541,7 @@ void main() { expect(processManager, hasNoRemainingExpectations); }, overrides: { ProcessManager: () => FakeProcessManager.any(), + Pub: () => fakePubBecauseRefreshPluginsList, FileSystem: () => fileSystem, Logger: () => logger, OperatingSystemUtils: () => os, @@ -578,6 +578,7 @@ void main() { expect(coreDeviceControl.argumentsUsedForLaunch, contains('--enable-dart-profiling')); }, overrides: { ProcessManager: () => FakeProcessManager.any(), + Pub: () => fakePubBecauseRefreshPluginsList, FileSystem: () => fileSystem, Logger: () => logger, OperatingSystemUtils: () => os, @@ -645,6 +646,7 @@ void main() { expect(processManager, hasNoRemainingExpectations); }, overrides: { ProcessManager: () => FakeProcessManager.any(), + Pub: () => fakePubBecauseRefreshPluginsList, FileSystem: () => fileSystem, Logger: () => logger, OperatingSystemUtils: () => os, @@ -721,6 +723,7 @@ void main() { expect(processManager, hasNoRemainingExpectations); }, overrides: { ProcessManager: () => FakeProcessManager.any(), + Pub: () => fakePubBecauseRefreshPluginsList, FileSystem: () => fileSystem, Logger: () => logger, OperatingSystemUtils: () => os, @@ -802,6 +805,7 @@ void main() { expect(contents.contains('CONFIGURATION_BUILD_DIR'), isFalse); }, overrides: { ProcessManager: () => FakeProcessManager.any(), + Pub: () => fakePubBecauseRefreshPluginsList, FileSystem: () => fileSystem, Logger: () => logger, OperatingSystemUtils: () => os, @@ -842,6 +846,7 @@ void main() { expect(processManager, hasNoRemainingExpectations); }, overrides: { ProcessManager: () => FakeProcessManager.any(), + Pub: () => fakePubBecauseRefreshPluginsList, FileSystem: () => fileSystem, Logger: () => logger, Platform: () => macPlatform, @@ -881,6 +886,7 @@ void main() { expect(processManager, hasNoRemainingExpectations); }, overrides: { ProcessManager: () => FakeProcessManager.any(), + Pub: () => fakePubBecauseRefreshPluginsList, FileSystem: () => fileSystem, Logger: () => logger, OperatingSystemUtils: () => os, diff --git a/packages/flutter_tools/test/general.shard/macos/cocoapod_utils_test.dart b/packages/flutter_tools/test/general.shard/macos/cocoapod_utils_test.dart index 454222d2477..fde5c90e4a3 100644 --- a/packages/flutter_tools/test/general.shard/macos/cocoapod_utils_test.dart +++ b/packages/flutter_tools/test/general.shard/macos/cocoapod_utils_test.dart @@ -8,6 +8,7 @@ import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/build_info.dart'; +import 'package:flutter_tools/src/dart/pub.dart'; import 'package:flutter_tools/src/flutter_manifest.dart'; import 'package:flutter_tools/src/macos/cocoapod_utils.dart'; import 'package:flutter_tools/src/macos/cocoapods.dart'; @@ -16,6 +17,7 @@ import 'package:test/fake.dart'; import '../../src/common.dart'; import '../../src/context.dart'; +import '../../src/fake_pub_deps.dart'; void main() { group('processPodsIfNeeded', () { @@ -107,7 +109,8 @@ void main() { expect(cocoaPods.processedPods, isTrue); }, overrides: { FileSystem: () => fs, - ProcessManager: () => FakeProcessManager.any(), + ProcessManager: FakeProcessManager.empty, + Pub: FakePubWithPrimedDeps.new, CocoaPods: () => cocoaPods, }); @@ -125,7 +128,8 @@ void main() { expect(cocoaPods.processedPods, isTrue); }, overrides: { FileSystem: () => fs, - ProcessManager: () => FakeProcessManager.any(), + ProcessManager: FakeProcessManager.empty, + Pub: FakePubWithPrimedDeps.new, CocoaPods: () => cocoaPods, }); @@ -142,7 +146,8 @@ void main() { expect(cocoaPods.processedPods, isFalse); }, overrides: { FileSystem: () => fs, - ProcessManager: () => FakeProcessManager.any(), + ProcessManager: FakeProcessManager.empty, + Pub: FakePubWithPrimedDeps.new, CocoaPods: () => cocoaPods, }); @@ -158,7 +163,8 @@ void main() { expect(cocoaPods.processedPods, isFalse); }, overrides: { FileSystem: () => fs, - ProcessManager: () => FakeProcessManager.any(), + ProcessManager: FakeProcessManager.empty, + Pub: FakePubWithPrimedDeps.new, CocoaPods: () => cocoaPods, }); }); @@ -182,7 +188,8 @@ void main() { expect(cocoaPods.processedPods, isTrue); }, overrides: { FileSystem: () => fs, - ProcessManager: () => FakeProcessManager.any(), + ProcessManager: FakeProcessManager.empty, + Pub: FakePubWithPrimedDeps.new, CocoaPods: () => cocoaPods, }); @@ -203,7 +210,7 @@ void main() { expect(cocoaPods.processedPods, isFalse); }, overrides: { FileSystem: () => fs, - ProcessManager: () => FakeProcessManager.any(), + ProcessManager: FakeProcessManager.empty, CocoaPods: () => cocoaPods, }); @@ -235,7 +242,8 @@ void main() { ); }, overrides: { FileSystem: () => fs, - ProcessManager: () => FakeProcessManager.any(), + ProcessManager: FakeProcessManager.empty, + Pub: FakePubWithPrimedDeps.new, CocoaPods: () => cocoaPods, Logger: () => logger, }); @@ -260,7 +268,8 @@ void main() { expect(cocoaPods.processedPods, isTrue); }, overrides: { FileSystem: () => fs, - ProcessManager: () => FakeProcessManager.any(), + ProcessManager: FakeProcessManager.empty, + Pub: FakePubWithPrimedDeps.new, CocoaPods: () => cocoaPods, }); @@ -278,7 +287,8 @@ void main() { expect(cocoaPods.processedPods, isTrue); }, overrides: { FileSystem: () => fs, - ProcessManager: () => FakeProcessManager.any(), + ProcessManager: FakeProcessManager.empty, + Pub: FakePubWithPrimedDeps.new, CocoaPods: () => cocoaPods, }); @@ -295,7 +305,8 @@ void main() { expect(cocoaPods.processedPods, isFalse); }, overrides: { FileSystem: () => fs, - ProcessManager: () => FakeProcessManager.any(), + ProcessManager: FakeProcessManager.empty, + Pub: FakePubWithPrimedDeps.new, CocoaPods: () => cocoaPods, }); @@ -311,7 +322,8 @@ void main() { expect(cocoaPods.processedPods, isFalse); }, overrides: { FileSystem: () => fs, - ProcessManager: () => FakeProcessManager.any(), + ProcessManager: FakeProcessManager.empty, + Pub: FakePubWithPrimedDeps.new, CocoaPods: () => cocoaPods, }); }); @@ -335,7 +347,8 @@ void main() { expect(cocoaPods.processedPods, isTrue); }, overrides: { FileSystem: () => fs, - ProcessManager: () => FakeProcessManager.any(), + ProcessManager: FakeProcessManager.empty, + Pub: FakePubWithPrimedDeps.new, CocoaPods: () => cocoaPods, }); @@ -356,7 +369,7 @@ void main() { expect(cocoaPods.processedPods, isFalse); }, overrides: { FileSystem: () => fs, - ProcessManager: () => FakeProcessManager.any(), + ProcessManager: FakeProcessManager.empty, CocoaPods: () => cocoaPods, }); @@ -388,7 +401,8 @@ void main() { ); }, overrides: { FileSystem: () => fs, - ProcessManager: () => FakeProcessManager.any(), + ProcessManager: FakeProcessManager.empty, + Pub: FakePubWithPrimedDeps.new, CocoaPods: () => cocoaPods, Logger: () => logger, }); diff --git a/packages/flutter_tools/test/general.shard/plugins_test.dart b/packages/flutter_tools/test/general.shard/plugins_test.dart index 6051e967bd8..08c07c4fa7a 100644 --- a/packages/flutter_tools/test/general.shard/plugins_test.dart +++ b/packages/flutter_tools/test/general.shard/plugins_test.dart @@ -14,6 +14,7 @@ import 'package:flutter_tools/src/base/os.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/base/time.dart'; import 'package:flutter_tools/src/base/utils.dart'; +import 'package:flutter_tools/src/dart/pub.dart'; import 'package:flutter_tools/src/features.dart'; import 'package:flutter_tools/src/flutter_manifest.dart'; import 'package:flutter_tools/src/flutter_plugins.dart'; @@ -30,6 +31,7 @@ import 'package:yaml/yaml.dart'; import '../src/common.dart'; import '../src/context.dart'; +import '../src/fake_pub_deps.dart'; import '../src/fakes.dart' hide FakeOperatingSystemUtils; import '../src/pubspec_schema.dart'; @@ -462,7 +464,8 @@ dependencies: expect(flutterProject.flutterPluginsDependenciesFile, exists); }, overrides: { FileSystem: () => fs, - ProcessManager: () => FakeProcessManager.any(), + ProcessManager: FakeProcessManager.empty, + Pub: FakePubWithPrimedDeps.new, }); testUsingContext( diff --git a/packages/flutter_tools/test/src/context.dart b/packages/flutter_tools/test/src/context.dart index 8207b601da8..6adfd1facbb 100644 --- a/packages/flutter_tools/test/src/context.dart +++ b/packages/flutter_tools/test/src/context.dart @@ -121,7 +121,7 @@ void testUsingContext( FileSystem: () => LocalFileSystemBlockingSetCurrentDirectory(), PlistParser: () => FakePlistParser(), Signals: () => FakeSignals(), - Pub: () => ThrowingPub(), // prevent accidentally using pub. + Pub: () => const ThrowingPub(), // prevent accidentally using pub. CrashReporter: () => const NoopCrashReporter(), TemplateRenderer: () => const MustacheTemplateRenderer(), BuildTargets: () => const BuildTargetsImpl(), diff --git a/packages/flutter_tools/test/src/fake_pub_deps.dart b/packages/flutter_tools/test/src/fake_pub_deps.dart new file mode 100644 index 00000000000..87e80cd35b6 --- /dev/null +++ b/packages/flutter_tools/test/src/fake_pub_deps.dart @@ -0,0 +1,84 @@ +// 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_tools/src/dart/pub.dart'; +import 'package:flutter_tools/src/project.dart'; + +/// A fake implementation of [Pub] with a pre-primed [deps] response. +final class FakePubWithPrimedDeps implements Pub { + /// Creates an implementation of [Pub] with a pre-primed [Pub.deps] response. + /// + /// It is expected that every [FlutterProject] that is provided to the + /// [Pub.deps] call is represented by [rootPackageName]. + /// + /// Optionally, provide [devDependencies] (of [rootPackageName]), and non + /// dev-dependencies ([dependencies]) of any package to a set of any other + /// packages. A resulting valid `dart pub deps --json` response is implicitly + /// created. + factory FakePubWithPrimedDeps({ + String rootPackageName = 'app_name', + Set devDependencies = const {}, + Map> dependencies = const >{}, + }) { + // Start the packages: [ ... ] list with the root package. + final List packages = [ + { + 'name': rootPackageName, + 'kind': 'root', + 'dependencies': [ + ...dependencies.keys, + ...devDependencies, + ]..sort(), + 'directDependencies': [ + ...?dependencies[rootPackageName], + ...devDependencies, + ]..sort(), + 'devDependencies': [ + ...devDependencies, + ], + }, + ]; + + // Add all non-dev dependencies. + for (final String packageName in dependencies.keys) { + final bool direct = dependencies[rootPackageName]!.contains(packageName); + packages.add({ + 'name': packageName, + 'kind': direct ? 'direct' : 'transitive', + 'dependencies': [ + ...?dependencies[packageName], + ], + 'directDependencies': [ + ...?dependencies[packageName], + ], + }); + } + + // Add all dev-dependencies. + for (final String packageName in devDependencies) { + packages.add({ + 'name': packageName, + 'kind': 'dev', + 'dependencies': [], + 'directDependencies': [], + }); + } + + return FakePubWithPrimedDeps._({ + 'root': rootPackageName, + 'packages': packages, + }); + } + + const FakePubWithPrimedDeps._(this._deps); + final Map _deps; + + @override + Future> deps(FlutterProject project) async => _deps; + + @override + Never noSuchMethod(Invocation invocation) { + throw UnsupportedError('Only .deps is expected to be called'); + } +} diff --git a/packages/flutter_tools/test/src/testbed.dart b/packages/flutter_tools/test/src/testbed.dart index 056de651778..b8b86c742cd 100644 --- a/packages/flutter_tools/test/src/testbed.dart +++ b/packages/flutter_tools/test/src/testbed.dart @@ -44,7 +44,7 @@ final Map _testbedDefaults = { Analytics: () => const NoOpAnalytics(), FlutterVersion: () => FakeFlutterVersion(), // prevent requirement to mock git for test runner. Signals: () => FakeSignals(), // prevent registering actual signal handlers. - Pub: () => ThrowingPub(), // prevent accidental invocations of pub. + Pub: () => const ThrowingPub(), // prevent accidental invocations of pub. }; /// Manages interaction with the tool injection and runner system. diff --git a/packages/flutter_tools/test/src/throwing_pub.dart b/packages/flutter_tools/test/src/throwing_pub.dart index 580722a8003..e3fc8be232b 100644 --- a/packages/flutter_tools/test/src/throwing_pub.dart +++ b/packages/flutter_tools/test/src/throwing_pub.dart @@ -3,47 +3,25 @@ // found in the LICENSE file. import 'package:flutter_tools/src/dart/pub.dart'; -import 'package:flutter_tools/src/project.dart'; -class ThrowingPub implements Pub { - @override - Future batch(List arguments, { - PubContext? context, - String? directory, - MessageFilter? filter, - String? failureMessage = 'pub failed', - }) { - throw UnsupportedError('Attempted to invoke pub during test.'); - } +final class ThrowingPub implements Pub { + const ThrowingPub(); @override - Future get({ - PubContext? context, - required FlutterProject project, - bool upgrade = false, - bool offline = false, - bool checkLastModified = true, - bool skipPubspecYamlCheck = false, - bool generateSyntheticPackage = false, - bool generateSyntheticPackageForExample = false, - String? flutterRootOverride, - bool checkUpToDate = false, - bool shouldSkipThirdPartyGenerator = true, - PubOutputMode outputMode = PubOutputMode.all, - }) { - throw UnsupportedError('Attempted to invoke pub during test.'); - } - - @override - Future interactively( - List arguments, { - FlutterProject? project, - required PubContext context, - required String command, - bool touchesPackageConfig = false, - bool generateSyntheticPackage = false, - PubOutputMode outputMode = PubOutputMode.all, - }) { - throw UnsupportedError('Attempted to invoke pub during test.'); + Never noSuchMethod(Invocation invocation) { + throw UnsupportedError( + 'Attempted to invoke pub during test, which otherwise was unexpected. ' + 'This error may be caused by either changing the implementation details ' + 'of the Flutter CLI in where the "Pub" class is now being used, or ' + 'adding a unit test that transitively depends on "Pub".\n' + '\n' + 'Possible options for resolution:\n' + ' 1. Refactor the code or test to not rely on "Pub".\n' + ' 2. Create and use a test-appropriate Fake (grep for "implements Pub") ' + ' for example code across the test/ repo. It is possible that the ' + ' file you are editing already has an appropriate Fake.\n' + ' 3. Use "FakePubWithPrimedDeps" if your code will transitively call ' + ' "dart pub deps --json" and you need a realistic output.', + ); } } From 364901da543160adbc7c2c7269d4978a356c2c44 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Wed, 13 Nov 2024 13:03:56 -0500 Subject: [PATCH 048/386] Roll Packages from 72356fda4684 to 26e123a6ce03 (19 revisions) (#158626) https://github.com/flutter/packages/compare/72356fda4684...26e123a6ce03 2024-11-13 dasyad00@gmail.com [camera_windows] Set device media type for video preview explicitly (flutter/packages#7447) 2024-11-13 39979207+ThangVuNguyenViet@users.noreply.github.com [go_router] Add support for relative routes (flutter/packages#6825) 2024-11-13 pq@users.noreply.github.com [vector_graphics_compiler] fix a renamed method parameter lint (flutter/packages#8070) 2024-11-12 feinstein@users.noreply.github.com [in_app_purchase] Add expiration date to Transaction (flutter/packages#8030) 2024-11-12 stuartmorgan@google.com [various] Clean up contributing guides (flutter/packages#8032) 2024-11-12 ditman@gmail.com [ci] Remove web renderer option from tools. (flutter/packages#8055) 2024-11-12 stuartmorgan@google.com [url_launcher] Update Pigeon version for Linux (flutter/packages#8065) 2024-11-12 tobias@leafnode.se [go_router] Add support for preloading branches of StatefulShellRoute (revised solution) (flutter/packages#6467) 2024-11-12 stuartmorgan@google.com [pigeon] Make Linux type declarations public (flutter/packages#8040) 2024-11-11 engine-flutter-autoroll@skia.org Roll Flutter from 73546b3b71a7 to c8510f29ccc2 (30 revisions) (flutter/packages#8042) 2024-11-11 magder@google.com Use dependabot multi-directory configuration for Android package updates (flutter/packages#8048) 2024-11-11 stuartmorgan@google.com [tools] Run `pub get` before `format` (flutter/packages#8052) 2024-11-11 stuartmorgan@google.com [file_selector] Fix Linux cancel regression (flutter/packages#8051) 2024-11-09 stuartmorgan@google.com [shared_preferences] Fix confusing language in README (flutter/packages#8049) 2024-11-08 magder@google.com Use dependabot multi-directory configuration for Android example gradle updates (flutter/packages#8036) 2024-11-08 43054281+camsim99@users.noreply.github.com [animations] Remove `.flutter-plugins` reference from example app (flutter/packages#8002) 2024-11-08 magder@google.com Group dependabot github-action update PRs, delete dead docker updates (flutter/packages#8044) 2024-11-08 37028599+EArminjon@users.noreply.github.com [vector_graphics_compiler] fix-null-exception (flutter/packages#8006) 2024-11-08 stuartmorgan@google.com [tools] Format Dart per-package (flutter/packages#8043) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-packages-flutter-autoroll Please CC flutter-ecosystem@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/flutter_packages.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/flutter_packages.version b/bin/internal/flutter_packages.version index fb97db04736..1a0a99d903e 100644 --- a/bin/internal/flutter_packages.version +++ b/bin/internal/flutter_packages.version @@ -1 +1 @@ -72356fda4684035d1a015f1ba16bc2f37d954d1e +26e123a6ce039da6b75fe4248e93c8aeeb6d395b From ed553d10cf6370065c12d372027ff2d0cf621cf1 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Wed, 13 Nov 2024 10:03:58 -0800 Subject: [PATCH 049/386] Avoid using platform `ProcessInfo.maxRss` in test. (#158526) Closes https://github.com/flutter/flutter/issues/157629. Avoids failures in the style: ```txt 00:37 +4597 ~3 -1: /Users/matanl/Developer/flutter/packages/flutter_tools/test/commands.shard/permeable/build_appbundle_test.dart: analytics logs success [E] Expected: contains Event:<{"eventName":"flutter_command_result","eventData":{"commandPath":"create","result":"success","commandHasTerminal":false,"maxRss":147013632}}> Actual: [ Event:{"eventName":"command_usage_values","eventData":{"workflow":"create","commandHasTerminal":false,"createProjectType":"app","createAndroidLanguage":"kotlin","createIosLanguage":"swift"}}, Event:{"eventName":"flutter_command_result","eventData":{"commandPath":"create","result":"success","commandHasTerminal":false,"maxRss":143261696}}, Event:{"eventName":"timing","eventData":{"workflow":"flutter","variableName":"create","elapsedMilliseconds":527,"label":"success"}}, Event:{"eventName":"command_usage_values","eventData":{"workflow":"appbundle","commandHasTerminal":false,"buildAppBundleTargetPlatform":"android-arm,android-arm64,android-x64","buildAppBundleBuildMode":"release"}}, Event:{"eventName":"flutter_command_result","eventData":{"commandPath":"appbundle","result":"success","commandHasTerminal":false,"maxRss":147013632}}, Event:{"eventName":"timing","eventData":{"workflow":"flutter","variableName":"appbundle","elapsedMilliseconds":10,"label":"success"}} ] Which: does not contain Event:<{"eventName":"flutter_command_result","eventData":{"commandPath":"create","result":"success","commandHasTerminal":false,"maxRss":147013632}}> ``` I am guessing is not guaranteed to be stable while running, and as a result is not. This stabilizes the value for a test that I believe does not care about getting the "real" value anyway. --- .../permeable/build_appbundle_test.dart | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) 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..861d03a6e9b 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,7 @@ void main() { overrides: { AndroidBuilder: () => FakeAndroidBuilder(), Analytics: () => fakeAnalytics, + ProcessInfo: () => processInfo, }); }); @@ -291,3 +295,8 @@ class FakeAndroidSdk extends Fake implements AndroidSdk { @override final Directory directory; } + +class FakeProcessInfo extends Fake implements ProcessInfo { + @override + int maxRss = 123456789; +} From e77093bba4f8c5cdc66eecb8a4d5f14ac8dec083 Mon Sep 17 00:00:00 2001 From: Nate Wilson Date: Wed, 13 Nov 2024 11:52:27 -0700 Subject: [PATCH 050/386] "Fix failing checks" wiki page for new contributors (#154629) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resolves https://github.com/flutter/flutter/issues/154628
As a contributor, I would expect resources related to testing to be located in the [/docs/contributing/testing](https://github.com/flutter/flutter/tree/master/docs/contributing/testing) directory. This PR adds a page to that directory geared toward helping new contributors.
I've noticed that in `team-framework` triage meetings, comments along the lines of "could you take a look at the failing checks?" are a regular occurrence. I believe we could save quite a bit of effort by changing this: > [**Understanding a LUCI build failure**](https://github.com/flutter/flutter/blob/a5ca16ea94048103b110d2cbd41e95d770735fb5/docs/infra/Understanding-a-LUCI-build-failure.md) to this: > [**Flutter wiki – How to fix failing checks**](https://github.com/nate-thegrate/flutter/blob/fix-checks-wiki-page/docs/contributing/testing/Fix-failing-checks.md) --- .../testing/Fix-failing-checks.md | 138 ++++++++++++++++++ .../Understanding-a-LUCI-build-failure.md | 2 + 2 files changed, 140 insertions(+) create mode 100644 docs/contributing/testing/Fix-failing-checks.md 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/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) From 7374452ecabd51d6bc87b96eba1898fee58d87f2 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Wed, 13 Nov 2024 10:55:47 -0800 Subject: [PATCH 051/386] Stream the output of `flutter build` for debugging. (#158757) Towards https://github.com/flutter/flutter/issues/158560. --- ...e_assets_without_cbuild_assemble_test.dart | 29 ++++++++++--------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart b/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart index 8f953c059f4..12ac06d09f5 100644 --- a/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart +++ b/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart @@ -5,6 +5,7 @@ import 'dart:io' as io; import 'package:file/file.dart'; +import 'package:flutter_tools/src/base/io.dart'; import 'package:process/process.dart'; import 'package:yaml/yaml.dart'; @@ -33,7 +34,6 @@ void main() { return; } - const ProcessManager processManager = LocalProcessManager(); final String constraint = _getPackageFfiTemplatePubspecVersion(); @@ -122,19 +122,22 @@ void main(List args) async { '''); // Try building. - await expectLater( - processManager.run( - [ - flutterBin, - 'build', - buildCommand, - '--debug', - if (!codeSign) '--no-codesign', - ], - workingDirectory: packageDirectory.path, - ), - completion(const ProcessResultMatcher()), + // + // TODO(matanlurey): Stream the app so that we can see partial output. + final List args = [ + flutterBin, + 'build', + buildCommand, + '--debug', + if (!codeSign) '--no-codesign', + ]; + io.stderr.writeln('Running $args...'); + final io.Process process = await processManager.start( + args, + workingDirectory: packageDirectory.path, + mode: ProcessStartMode.inheritStdio, ); + expect(await process.exitCode, 0); }); }, ); From cae3f9acd0d95e61afe2f9561640418d4e220549 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Wed, 13 Nov 2024 14:05:03 -0500 Subject: [PATCH 052/386] Roll Flutter Engine from db3e5af2ca22 to 82940a9aa714 (2 revisions) (#158799) https://github.com/flutter/engine/compare/db3e5af2ca22...82940a9aa714 2024-11-13 skia-flutter-autoroll@skia.org Roll Dart SDK from e5c2c502c890 to 66ab1774bfe9 (1 revision) (flutter/engine#56558) 2024-11-13 skia-flutter-autoroll@skia.org Roll Dart SDK from c7d140d18895 to e5c2c502c890 (1 revision) (flutter/engine#56555) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index d9f412749c5..cb38c48c413 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -db3e5af2ca2267183b71a8b68ba4ac2330e957a6 +82940a9aa71453e00e87f25c7d851260cbbd978d From d7e1f03ee0c2aaebbc99b415efefdb19d4e1c261 Mon Sep 17 00:00:00 2001 From: Alejandro Santiago Date: Wed, 13 Nov 2024 20:37:22 +0000 Subject: [PATCH 053/386] docs: include Human Interface haptic information in HapticFeedback (#158587) ## Description Adding reference to the Human Interface documentation about Haptics in the `HapticFeedback` docs. The Human Haptic Guidelines documentation are excellent since they provide visualizations that show how these different haptics actually are with some interactive demos, for example with Impact haptics (see image below). Such helps developers decide what haptic to go for and understand when they should be used. Screenshot 2024-11-13 at 15 13 10 --- .../lib/src/services/haptic_feedback.dart | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) 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', From 5a9c2b4dd1d9ccd22e87eeb2edcf03de74128f76 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Wed, 13 Nov 2024 12:57:13 -0800 Subject: [PATCH 054/386] Temporarily skip flutter build apk for native_assets tests. (#158880) Work around for https://github.com/flutter/flutter/issues/158560. --- .../isolated/native_assets_without_cbuild_assemble_test.dart | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart b/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart index 12ac06d09f5..e0ce987e7f3 100644 --- a/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart +++ b/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart @@ -138,8 +138,11 @@ void main(List args) async { mode: ProcessStartMode.inheritStdio, ); expect(await process.exitCode, 0); - }); + },); }, + // TODO(matanlurey): Debug why flutter build apk often timesout. + // See https://github.com/flutter/flutter/issues/158560 for details. + skip: buildCommand == 'apk' ? 'flutter build apk times out' : false, ); } From 8a55c941cf858e868826f0048d4464bf71bb68e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Sharma?= <737941+loic-sharma@users.noreply.github.com> Date: Wed, 13 Nov 2024 13:45:07 -0800 Subject: [PATCH 055/386] [SwiftPM] Move the logic for SwiftPM enablement to the platform project (#158213) In the future, it will be possible for Swift Package Manager to be enabled on one but not all platforms (see https://github.com/flutter/flutter/issues/151567#issuecomment-2455941279). This moves the `usesSwiftPackageManager` property from the platform-agnostic `Project` to the platform-specific `IosProject` and `MacOSProject`. This will allow the `IosProject` and `MacOSProject` to return different values for `usesSwiftPackageManager` in the future. For now, both of these projects will always return the same value. Part of https://github.com/flutter/flutter/issues/151567 --- .../lib/src/flutter_plugins.dart | 16 +- packages/flutter_tools/lib/src/ios/mac.dart | 8 +- .../lib/src/macos/build_macos.dart | 4 +- .../lib/src/macos/cocoapod_utils.dart | 4 +- .../lib/src/macos/cocoapods.dart | 2 +- .../macos/darwin_dependency_management.dart | 8 +- packages/flutter_tools/lib/src/project.dart | 19 -- .../flutter_tools/lib/src/xcode_project.dart | 37 ++++ .../test/general.shard/ios/mac_test.dart | 15 +- .../macos/cocoapod_utils_test.dart | 25 +-- .../darwin_dependency_management_test.dart | 31 ++-- .../test/general.shard/plugins_test.dart | 71 +++++++- .../test/general.shard/project_test.dart | 98 ---------- .../general.shard/xcode_project_test.dart | 169 +++++++++++++++++- 14 files changed, 341 insertions(+), 166 deletions(-) diff --git a/packages/flutter_tools/lib/src/flutter_plugins.dart b/packages/flutter_tools/lib/src/flutter_plugins.dart index 471dba42f92..fcd45e26d86 100644 --- a/packages/flutter_tools/lib/src/flutter_plugins.dart +++ b/packages/flutter_tools/lib/src/flutter_plugins.dart @@ -1071,12 +1071,22 @@ Future refreshPluginsList( // Write the legacy plugin files to avoid breaking existing apps. final bool legacyChanged = useImplicitPubspecResolution && _writeFlutterPluginsListLegacy(project, plugins); - final bool swiftPackageManagerEnabled = !forceCocoaPodsOnly && project.usesSwiftPackageManager; + 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, - swiftPackageManagerEnabledIos: swiftPackageManagerEnabled, - swiftPackageManagerEnabledMacos: swiftPackageManagerEnabled, + swiftPackageManagerEnabledIos: swiftPackageManagerEnabledIos, + swiftPackageManagerEnabledMacos: swiftPackageManagerEnabledMacos, ); if (changed || legacyChanged || forceCocoaPodsOnly) { createPluginSymlinks(project, force: true); diff --git a/packages/flutter_tools/lib/src/ios/mac.dart b/packages/flutter_tools/lib/src/ios/mac.dart index 523555533f9..06be3d76ff0 100644 --- a/packages/flutter_tools/lib/src/ios/mac.dart +++ b/packages/flutter_tools/lib/src/ios/mac.dart @@ -166,7 +166,7 @@ Future buildXcodeProject({ RemoveBitcodeMigration(app.project, globals.logger), XcodeThinBinaryBuildPhaseInputPathsMigration(app.project, globals.logger), UIApplicationMainDeprecationMigration(app.project, globals.logger), - if (project.usesSwiftPackageManager && app.project.flutterPluginSwiftPackageManifest.existsSync()) + if (app.project.usesSwiftPackageManager && app.project.flutterPluginSwiftPackageManifest.existsSync()) SwiftPackageManagerIntegrationMigration( app.project, SupportedPlatform.ios, @@ -267,7 +267,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 +888,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 +906,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) { diff --git a/packages/flutter_tools/lib/src/macos/build_macos.dart b/packages/flutter_tools/lib/src/macos/build_macos.dart index 5b8b186a238..f268a928cc4 100644 --- a/packages/flutter_tools/lib/src/macos/build_macos.dart +++ b/packages/flutter_tools/lib/src/macos/build_macos.dart @@ -91,7 +91,7 @@ Future buildMacOS({ FlutterApplicationMigration(flutterProject.macos, globals.logger), NSApplicationMainDeprecationMigration(flutterProject.macos, globals.logger), SecureRestorableStateMigration(flutterProject.macos, globals.logger), - if (flutterProject.usesSwiftPackageManager && flutterProject.macos.flutterPluginSwiftPackageManifest.existsSync()) + if (flutterProject.macos.usesSwiftPackageManager && flutterProject.macos.flutterPluginSwiftPackageManifest.existsSync()) SwiftPackageManagerIntegrationMigration( flutterProject.macos, SupportedPlatform.macos, @@ -145,7 +145,7 @@ Future buildMacOS({ useMacOSConfig: true, ); - if (flutterProject.usesSwiftPackageManager) { + if (flutterProject.macos.usesSwiftPackageManager) { final String? macOSDeploymentTarget = buildSettings['MACOSX_DEPLOYMENT_TARGET']; if (macOSDeploymentTarget != null) { SwiftPackageManager.updateMinimumDeployment( diff --git a/packages/flutter_tools/lib/src/macos/cocoapod_utils.dart b/packages/flutter_tools/lib/src/macos/cocoapod_utils.dart index fc78aee9917..007d6206c88 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; @@ -50,7 +50,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..8bfd56bbac1 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'); 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 c681308743d..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,7 +89,7 @@ class DarwinDependencyManagement { ); final bool useCocoapods; - if (_project.usesSwiftPackageManager) { + if (xcodeProject.usesSwiftPackageManager) { useCocoapods = swiftPackageCount < totalCount; } else { // When Swift Package Manager is not enabled, set up Podfile if plugins @@ -161,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( @@ -175,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/project.dart b/packages/flutter_tools/lib/src/project.dart index d1462587a3e..12e10760835 100644 --- a/packages/flutter_tools/lib/src/project.dart +++ b/packages/flutter_tools/lib/src/project.dart @@ -21,7 +21,6 @@ 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'; @@ -262,24 +261,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 [ 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/test/general.shard/ios/mac_test.dart b/packages/flutter_tools/test/general.shard/ios/mac_test.dart index 0bb34760922..a6cef39e789 100644 --- a/packages/flutter_tools/test/general.shard/ios/mac_test.dart +++ b/packages/flutter_tools/test/general.shard/ios/mac_test.dart @@ -816,6 +816,7 @@ void createFakePlugins( class FakeIosProject extends Fake implements IosProject { FakeIosProject({ required MemoryFileSystem fileSystem, + this.usesSwiftPackageManager = false, }) : hostAppRoot = fileSystem.directory('app_name').childDirectory('ios'); @override @@ -832,6 +833,9 @@ class FakeIosProject extends Fake implements IosProject { @override File get podfile => hostAppRoot.childFile('Podfile'); + + @override + final bool usesSwiftPackageManager; } class FakeFlutterProject extends Fake implements FlutterProject { @@ -841,7 +845,8 @@ class FakeFlutterProject extends Fake implements FlutterProject { this.isModule = false, }); - MemoryFileSystem fileSystem; + final MemoryFileSystem fileSystem; + final bool usesSwiftPackageManager; @override late final Directory directory = fileSystem.directory('app_name'); @@ -856,10 +861,10 @@ class FakeFlutterProject extends Fake implements FlutterProject { File get flutterPluginsDependenciesFile => directory.childFile('.flutter-plugins-dependencies'); @override - late final IosProject ios = FakeIosProject(fileSystem: fileSystem); - - @override - final bool usesSwiftPackageManager; + late final IosProject ios = FakeIosProject( + fileSystem: fileSystem, + usesSwiftPackageManager: usesSwiftPackageManager, + ); @override final bool isModule; diff --git a/packages/flutter_tools/test/general.shard/macos/cocoapod_utils_test.dart b/packages/flutter_tools/test/general.shard/macos/cocoapod_utils_test.dart index fde5c90e4a3..aa07bd3b1c9 100644 --- a/packages/flutter_tools/test/general.shard/macos/cocoapod_utils_test.dart +++ b/packages/flutter_tools/test/general.shard/macos/cocoapod_utils_test.dart @@ -177,7 +177,7 @@ void main() { 'plugin_one', 'plugin_two' ]); - flutterProject.usesSwiftPackageManager = true; + flutterProject.ios.usesSwiftPackageManager = true; flutterProject.ios.podfile.createSync(recursive: true); await processPodsIfNeeded( @@ -200,7 +200,7 @@ void main() { 'plugin_one', 'plugin_two' ]); - flutterProject.usesSwiftPackageManager = true; + flutterProject.ios.usesSwiftPackageManager = true; await processPodsIfNeeded( flutterProject.ios, @@ -221,7 +221,7 @@ void main() { 'plugin_one', 'plugin_two' ]); - flutterProject.usesSwiftPackageManager = true; + flutterProject.ios.usesSwiftPackageManager = true; flutterProject.ios.flutterPluginSwiftPackageManifest.createSync(recursive: true); await processPodsIfNeeded( @@ -336,7 +336,7 @@ void main() { 'plugin_one', 'plugin_two' ]); - flutterProject.usesSwiftPackageManager = true; + flutterProject.macos.usesSwiftPackageManager = true; flutterProject.macos.podfile.createSync(recursive: true); await processPodsIfNeeded( @@ -359,7 +359,7 @@ void main() { 'plugin_one', 'plugin_two' ]); - flutterProject.usesSwiftPackageManager = true; + flutterProject.macos.usesSwiftPackageManager = true; await processPodsIfNeeded( flutterProject.macos, @@ -380,7 +380,7 @@ void main() { 'plugin_one', 'plugin_two' ]); - flutterProject.usesSwiftPackageManager = true; + flutterProject.macos.usesSwiftPackageManager = true; flutterProject.macos.flutterPluginSwiftPackageManifest.createSync(recursive: true); await processPodsIfNeeded( @@ -420,9 +420,6 @@ class FakeFlutterProject extends Fake implements FlutterProject { @override bool isModule = false; - @override - bool usesSwiftPackageManager = false; - @override late FlutterManifest manifest; @@ -436,10 +433,10 @@ class FakeFlutterProject extends Fake implements FlutterProject { late File flutterPluginsDependenciesFile; @override - late IosProject ios; + late FakeIosProject ios; @override - late MacOSProject macos; + late FakeMacOSProject macos; @override late AndroidProject android; @@ -489,6 +486,9 @@ class FakeMacOSProject extends Fake implements MacOSProject { .childDirectory('Packages') .childDirectory('FlutterGeneratedPluginSwiftPackage') .childFile('Package.swift'); + + @override + bool usesSwiftPackageManager = false; } class FakeIosProject extends Fake implements IosProject { @@ -527,6 +527,9 @@ class FakeIosProject extends Fake implements IosProject { .childDirectory('Packages') .childDirectory('FlutterGeneratedPluginSwiftPackage') .childFile('Package.swift'); + + @override + bool usesSwiftPackageManager = false; } class FakeAndroidProject extends Fake implements AndroidProject { diff --git a/packages/flutter_tools/test/general.shard/macos/darwin_dependency_management_test.dart b/packages/flutter_tools/test/general.shard/macos/darwin_dependency_management_test.dart index ba539c3e1e8..c4acf599481 100644 --- a/packages/flutter_tools/test/general.shard/macos/darwin_dependency_management_test.dart +++ b/packages/flutter_tools/test/general.shard/macos/darwin_dependency_management_test.dart @@ -505,6 +505,7 @@ void main() { class FakeIosProject extends Fake implements IosProject { FakeIosProject({ required MemoryFileSystem fileSystem, + required this.usesSwiftPackageManager, }) : hostAppRoot = fileSystem.directory('app_name').childDirectory('ios'); @override @@ -530,6 +531,9 @@ class FakeIosProject extends Fake implements IosProject { .contains('FlutterGeneratedPluginSwiftPackage'); } + @override + bool usesSwiftPackageManager; + @override Directory get managedDirectory => hostAppRoot.childDirectory('Flutter'); @@ -540,6 +544,7 @@ class FakeIosProject extends Fake implements IosProject { class FakeMacOSProject extends Fake implements MacOSProject { FakeMacOSProject({ required MemoryFileSystem fileSystem, + required this.usesSwiftPackageManager, }) : hostAppRoot = fileSystem.directory('app_name').childDirectory('macos'); @override @@ -565,6 +570,9 @@ class FakeMacOSProject extends Fake implements MacOSProject { .contains('FlutterGeneratedPluginSwiftPackage'); } + @override + bool usesSwiftPackageManager; + @override Directory get managedDirectory => hostAppRoot.childDirectory('Flutter'); @@ -579,18 +587,21 @@ class FakeFlutterProject extends Fake implements FlutterProject { this.isModule = false, }); - MemoryFileSystem fileSystem; - - - @override - late final IosProject ios = FakeIosProject(fileSystem: fileSystem); - - @override - late final MacOSProject macos = FakeMacOSProject(fileSystem: fileSystem); - - @override + final MemoryFileSystem fileSystem; final bool usesSwiftPackageManager; + @override + late final FakeIosProject ios = FakeIosProject( + fileSystem: fileSystem, + usesSwiftPackageManager: usesSwiftPackageManager, + ); + + @override + late final FakeMacOSProject macos = FakeMacOSProject( + fileSystem: fileSystem, + usesSwiftPackageManager: usesSwiftPackageManager, + ); + @override final bool isModule; } diff --git a/packages/flutter_tools/test/general.shard/plugins_test.dart b/packages/flutter_tools/test/general.shard/plugins_test.dart index 08c07c4fa7a..8c38156dbac 100644 --- a/packages/flutter_tools/test/general.shard/plugins_test.dart +++ b/packages/flutter_tools/test/general.shard/plugins_test.dart @@ -667,9 +667,15 @@ dependencies: final DateTime dateCreated = DateTime(1970); systemClock.currentTime = dateCreated; - flutterProject.usesSwiftPackageManager = true; + iosProject.usesSwiftPackageManager = true; + macosProject.usesSwiftPackageManager = true; - await refreshPluginsList(flutterProject, useImplicitPubspecResolution: true); + await refreshPluginsList( + flutterProject, + iosPlatform: true, + macOSPlatform: true, + useImplicitPubspecResolution: true, + ); expect(flutterProject.flutterPluginsDependenciesFile.existsSync(), true); final String pluginsString = flutterProject.flutterPluginsDependenciesFile @@ -711,7 +717,8 @@ dependencies: final DateTime dateCreated = DateTime(1970); systemClock.currentTime = dateCreated; - flutterProject.usesSwiftPackageManager = true; + iosProject.usesSwiftPackageManager = true; + macosProject.usesSwiftPackageManager = true; await refreshPluginsList(flutterProject, forceCocoaPodsOnly: true, useImplicitPubspecResolution: true); @@ -735,6 +742,55 @@ dependencies: FlutterVersion: () => flutterVersion, }); + testUsingContext( + '.flutter-plugins-dependencies can have different swift_package_manager_enabled values for iOS and macoS', () async { + createPlugin( + name: 'plugin-a', + platforms: const { + // Native-only; should include native build. + 'android': _PluginPlatformInfo(pluginClass: 'Foo', androidPackage: 'bar.foo'), + // Hybrid native and Dart; should include native build. + 'ios': _PluginPlatformInfo(pluginClass: 'Foo', dartPluginClass: 'Bar', sharedDarwinSource: true), + // Web; should not have the native build key at all since it doesn't apply. + 'web': _PluginPlatformInfo(pluginClass: 'Foo', fileName: 'lib/foo.dart'), + // Dart-only; should not include native build. + 'windows': _PluginPlatformInfo(dartPluginClass: 'Foo'), + }); + iosProject.testExists = true; + + final DateTime dateCreated = DateTime(1970); + systemClock.currentTime = dateCreated; + + iosProject.usesSwiftPackageManager = true; + macosProject.usesSwiftPackageManager = false; + + await refreshPluginsList( + flutterProject, + iosPlatform: true, + macOSPlatform: true, + useImplicitPubspecResolution: true, + ); + + expect(flutterProject.flutterPluginsDependenciesFile.existsSync(), true); + final String pluginsString = flutterProject.flutterPluginsDependenciesFile + .readAsStringSync(); + final Map jsonContent = json.decode(pluginsString) as Map; + + final Map expectedSwiftPackageManagerEnabled = { + 'ios': true, + 'macos': false, + }; + expect( + jsonContent['swift_package_manager_enabled'], + expectedSwiftPackageManagerEnabled, + ); + }, overrides: { + FileSystem: () => fs, + ProcessManager: () => FakeProcessManager.any(), + SystemClock: () => systemClock, + FlutterVersion: () => flutterVersion, + }); + testUsingContext('Changes to the plugin list invalidates the Cocoapod lockfiles', () async { simulatePodInstallRun(iosProject); simulatePodInstallRun(macosProject); @@ -2108,9 +2164,6 @@ class FakeFlutterProject extends Fake implements FlutterProject { @override bool isModule = false; - @override - bool usesSwiftPackageManager = false; - @override late FlutterManifest manifest; @@ -2154,6 +2207,9 @@ class FakeMacOSProject extends Fake implements MacOSProject { @override late File podManifestLock; + @override + bool usesSwiftPackageManager = false; + @override late Directory managedDirectory; @@ -2187,6 +2243,9 @@ class FakeIosProject extends Fake implements IosProject { @override late File podManifestLock; + + @override + bool usesSwiftPackageManager = false; } class FakeAndroidProject extends Fake implements AndroidProject { diff --git a/packages/flutter_tools/test/general.shard/project_test.dart b/packages/flutter_tools/test/general.shard/project_test.dart index 7203f9d8479..6c1e8f15ae6 100644 --- a/packages/flutter_tools/test/general.shard/project_test.dart +++ b/packages/flutter_tools/test/general.shard/project_test.dart @@ -375,91 +375,6 @@ void main() { }); }); - group('usesSwiftPackageManager', () { - testUsingContext('is true when iOS project exists', () async { - final MemoryFileSystem fs = MemoryFileSystem.test(); - final Directory projectDirectory = fs.directory('path'); - projectDirectory.childDirectory('ios').createSync(recursive: true); - final FlutterManifest manifest = FakeFlutterManifest(); - final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); - expect(project.usesSwiftPackageManager, isTrue); - }, overrides: { - FeatureFlags: () => TestFeatureFlags(isSwiftPackageManagerEnabled: true), - XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(15, 0, 0)), - }); - - testUsingContext('is true when macOS project exists', () async { - final MemoryFileSystem fs = MemoryFileSystem.test(); - final Directory projectDirectory = fs.directory('path'); - projectDirectory.childDirectory('macos').createSync(recursive: true); - final FlutterManifest manifest = FakeFlutterManifest(); - final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); - expect(project.usesSwiftPackageManager, isTrue); - }, overrides: { - FeatureFlags: () => TestFeatureFlags(isSwiftPackageManagerEnabled: true), - XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(15, 0, 0)), - }); - - testUsingContext('is false when disabled via manifest', () async { - final MemoryFileSystem fs = MemoryFileSystem.test(); - final Directory projectDirectory = fs.directory('path'); - projectDirectory.childDirectory('ios').createSync(recursive: true); - final FlutterManifest manifest = FakeFlutterManifest(disabledSwiftPackageManager: true); - final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); - expect(project.usesSwiftPackageManager, isFalse); - }, overrides: { - FeatureFlags: () => TestFeatureFlags(isSwiftPackageManagerEnabled: true), - XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(15, 0, 0)), - }); - - testUsingContext("is false when iOS and macOS project don't exist", () async { - final MemoryFileSystem fs = MemoryFileSystem.test(); - final Directory projectDirectory = fs.directory('path'); - final FlutterManifest manifest = FakeFlutterManifest(); - final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); - expect(project.usesSwiftPackageManager, isFalse); - }, overrides: { - FeatureFlags: () => TestFeatureFlags(isSwiftPackageManagerEnabled: true), - XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(15, 0, 0)), - }); - - testUsingContext('is false when Xcode is less than 15', () async { - final MemoryFileSystem fs = MemoryFileSystem.test(); - final Directory projectDirectory = fs.directory('path'); - projectDirectory.childDirectory('ios').createSync(recursive: true); - final FlutterManifest manifest = FakeFlutterManifest(); - final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); - expect(project.usesSwiftPackageManager, isFalse); - }, overrides: { - FeatureFlags: () => TestFeatureFlags(isSwiftPackageManagerEnabled: true), - XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(14, 0, 0)), - }); - - testUsingContext('is false when Swift Package Manager feature is not enabled', () async { - final MemoryFileSystem fs = MemoryFileSystem.test(); - final Directory projectDirectory = fs.directory('path'); - projectDirectory.childDirectory('ios').createSync(recursive: true); - final FlutterManifest manifest = FakeFlutterManifest(); - final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); - expect(project.usesSwiftPackageManager, isFalse); - }, overrides: { - FeatureFlags: () => TestFeatureFlags(), - XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(15, 0, 0)), - }); - - testUsingContext('is false when project is a module', () async { - final MemoryFileSystem fs = MemoryFileSystem.test(); - final Directory projectDirectory = fs.directory('path'); - projectDirectory.childDirectory('ios').createSync(recursive: true); - final FlutterManifest manifest = FakeFlutterManifest(isModule: true); - final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); - expect(project.usesSwiftPackageManager, isFalse); - }, overrides: { - FeatureFlags: () => TestFeatureFlags(isSwiftPackageManagerEnabled: true), - XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(15, 0, 0)), - }); - }); - group('java gradle agp compatibility', () { Future configureGradleAgpForTest({ required String gradleV, @@ -1896,16 +1811,3 @@ class FakeAndroidSdkWithDir extends Fake implements AndroidSdk { @override Directory get directory => _directory; } - -class FakeFlutterManifest extends Fake implements FlutterManifest { - FakeFlutterManifest({ - this.disabledSwiftPackageManager = false, - this.isModule = false, - }); - - @override - bool disabledSwiftPackageManager; - - @override - bool isModule; -} diff --git a/packages/flutter_tools/test/general.shard/xcode_project_test.dart b/packages/flutter_tools/test/general.shard/xcode_project_test.dart index dfaf6096ccc..fc8033fac8e 100644 --- a/packages/flutter_tools/test/general.shard/xcode_project_test.dart +++ b/packages/flutter_tools/test/general.shard/xcode_project_test.dart @@ -6,13 +6,16 @@ import 'package:file/file.dart'; 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/base/version.dart'; +import 'package:flutter_tools/src/features.dart'; +import 'package:flutter_tools/src/flutter_manifest.dart'; import 'package:flutter_tools/src/ios/xcodeproj.dart'; import 'package:flutter_tools/src/project.dart'; import 'package:test/fake.dart'; import '../src/common.dart'; import '../src/context.dart'; - +import '../src/fakes.dart'; void main() { group('IosProject', () { @@ -127,6 +130,79 @@ void main() { XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(), }); }); + + group('usesSwiftPackageManager', () { + testUsingContext('is true when iOS project exists', () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final Directory projectDirectory = fs.directory('path'); + projectDirectory.childDirectory('ios').createSync(recursive: true); + final FlutterManifest manifest = FakeFlutterManifest(); + final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); + expect(project.ios.usesSwiftPackageManager, isTrue); + }, overrides: { + FeatureFlags: () => TestFeatureFlags(isSwiftPackageManagerEnabled: true), + XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(15, 0, 0)), + }); + + testUsingContext("is false when iOS project doesn't exist", () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final Directory projectDirectory = fs.directory('path'); + final FlutterManifest manifest = FakeFlutterManifest(); + final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); + expect(project.ios.usesSwiftPackageManager, isFalse); + }, overrides: { + FeatureFlags: () => TestFeatureFlags(isSwiftPackageManagerEnabled: true), + XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(15, 0, 0)), + }); + + testUsingContext('is false when disabled via manifest', () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final Directory projectDirectory = fs.directory('path'); + projectDirectory.childDirectory('ios').createSync(recursive: true); + final FlutterManifest manifest = FakeFlutterManifest(disabledSwiftPackageManager: true); + final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); + expect(project.ios.usesSwiftPackageManager, isFalse); + }, overrides: { + FeatureFlags: () => TestFeatureFlags(isSwiftPackageManagerEnabled: true), + XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(15, 0, 0)), + }); + + testUsingContext('is false when Xcode is less than 15', () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final Directory projectDirectory = fs.directory('path'); + projectDirectory.childDirectory('ios').createSync(recursive: true); + final FlutterManifest manifest = FakeFlutterManifest(); + final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); + expect(project.ios.usesSwiftPackageManager, isFalse); + }, overrides: { + FeatureFlags: () => TestFeatureFlags(isSwiftPackageManagerEnabled: true), + XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(14, 0, 0)), + }); + + testUsingContext('is false when Swift Package Manager feature is not enabled', () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final Directory projectDirectory = fs.directory('path'); + projectDirectory.childDirectory('ios').createSync(recursive: true); + final FlutterManifest manifest = FakeFlutterManifest(); + final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); + expect(project.ios.usesSwiftPackageManager, isFalse); + }, overrides: { + FeatureFlags: () => TestFeatureFlags(), + XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(15, 0, 0)), + }); + + testUsingContext('is false when project is a module', () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final Directory projectDirectory = fs.directory('path'); + projectDirectory.childDirectory('ios').createSync(recursive: true); + final FlutterManifest manifest = FakeFlutterManifest(isModule: true); + final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); + expect(project.ios.usesSwiftPackageManager, isFalse); + }, overrides: { + FeatureFlags: () => TestFeatureFlags(isSwiftPackageManagerEnabled: true), + XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(15, 0, 0)), + }); + }); }); group('MacOSProject', () { @@ -175,6 +251,80 @@ void main() { 'app_name/macos/Flutter/Flutter-Debug.xcconfig', ); }); + + group('usesSwiftPackageManager', () { + testUsingContext('is true when macOS project exists', () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final Directory projectDirectory = fs.directory('path'); + projectDirectory.childDirectory('macos').createSync(recursive: true); + final FlutterManifest manifest = FakeFlutterManifest(); + final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); + expect(project.macos.usesSwiftPackageManager, isTrue); + }, overrides: { + FeatureFlags: () => TestFeatureFlags(isSwiftPackageManagerEnabled: true), + XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(15, 0, 0)), + }); + + testUsingContext("is false when macOS project doesn't exist", () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final Directory projectDirectory = fs.directory('path'); + final FlutterManifest manifest = FakeFlutterManifest(); + final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); + expect(project.ios.usesSwiftPackageManager, isFalse); + expect(project.macos.usesSwiftPackageManager, isFalse); + }, overrides: { + FeatureFlags: () => TestFeatureFlags(isSwiftPackageManagerEnabled: true), + XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(15, 0, 0)), + }); + + testUsingContext('is false when disabled via manifest', () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final Directory projectDirectory = fs.directory('path'); + projectDirectory.childDirectory('macos').createSync(recursive: true); + final FlutterManifest manifest = FakeFlutterManifest(disabledSwiftPackageManager: true); + final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); + expect(project.macos.usesSwiftPackageManager, isFalse); + }, overrides: { + FeatureFlags: () => TestFeatureFlags(isSwiftPackageManagerEnabled: true), + XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(15, 0, 0)), + }); + + testUsingContext('is false when Xcode is less than 15', () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final Directory projectDirectory = fs.directory('path'); + projectDirectory.childDirectory('macos').createSync(recursive: true); + final FlutterManifest manifest = FakeFlutterManifest(); + final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); + expect(project.macos.usesSwiftPackageManager, isFalse); + }, overrides: { + FeatureFlags: () => TestFeatureFlags(isSwiftPackageManagerEnabled: true), + XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(14, 0, 0)), + }); + + testUsingContext('is false when Swift Package Manager feature is not enabled', () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final Directory projectDirectory = fs.directory('path'); + projectDirectory.childDirectory('macos').createSync(recursive: true); + final FlutterManifest manifest = FakeFlutterManifest(); + final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); + expect(project.macos.usesSwiftPackageManager, isFalse); + }, overrides: { + FeatureFlags: () => TestFeatureFlags(), + XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(15, 0, 0)), + }); + + testUsingContext('is false when project is a module', () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final Directory projectDirectory = fs.directory('path'); + projectDirectory.childDirectory('macos').createSync(recursive: true); + final FlutterManifest manifest = FakeFlutterManifest(isModule: true); + final FlutterProject project = FlutterProject(projectDirectory, manifest, manifest); + expect(project.macos.usesSwiftPackageManager, isFalse); + }, overrides: { + FeatureFlags: () => TestFeatureFlags(isSwiftPackageManagerEnabled: true), + XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(version: Version(15, 0, 0)), + }); + }); }); } @@ -196,11 +346,15 @@ class FakeFlutterProject extends Fake implements FlutterProject { class FakeXcodeProjectInterpreter extends Fake implements XcodeProjectInterpreter { FakeXcodeProjectInterpreter({ this.isInstalled = true, + this.version, }); @override final bool isInstalled; + @override + final Version? version; + @override Future getInfo(String projectPath, {String? projectFilename}) async { return XcodeProjectInfo( @@ -211,3 +365,16 @@ class FakeXcodeProjectInterpreter extends Fake implements XcodeProjectInterprete ); } } + +class FakeFlutterManifest extends Fake implements FlutterManifest { + FakeFlutterManifest({ + this.disabledSwiftPackageManager = false, + this.isModule = false, + }); + + @override + bool disabledSwiftPackageManager; + + @override + bool isModule; +} From 3a075deeded897f526a0f3f309ec1d9b4b6cf535 Mon Sep 17 00:00:00 2001 From: "auto-submit[bot]" <98614782+auto-submit[bot]@users.noreply.github.com> Date: Wed, 13 Nov 2024 22:38:17 +0000 Subject: [PATCH 056/386] Reverts "Marks Mac_arm64_ios hot_mode_dev_cycle_ios__benchmark to be flaky (#158242)" (#158891) Reverts: flutter/flutter#158242 Initiated by: LouiseHsu Reason for reverting: Flake rate is low, and the arm64 macs in the staging pools are having difficulties Original PR Author: fluttergithubbot Reviewed By: {LouiseHsu} This change reverts the following previous change: Issue link: https://github.com/flutter/flutter/issues/158241 --- .ci.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/.ci.yaml b/.ci.yaml index a89c21cc957..da9363eecd4 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -5212,7 +5212,6 @@ targets: task_name: hot_mode_dev_cycle_ios__benchmark - name: Mac_arm64_ios hot_mode_dev_cycle_ios__benchmark - bringup: true # Flaky https://github.com/flutter/flutter/issues/158241 recipe: devicelab/devicelab_drone presubmit: false timeout: 60 From 5f93a7f7ea981f316b54be5d4b9315010f4819a3 Mon Sep 17 00:00:00 2001 From: Mitchell Goodwin <58190796+MitchellGoodwin@users.noreply.github.com> Date: Wed, 13 Nov 2024 14:38:56 -0800 Subject: [PATCH 057/386] Adds a skip message for analyzer (#158890) #158880 causes the linux analyzer to complain for not having a skip message. --- .../isolated/native_assets_without_cbuild_assemble_test.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart b/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart index e0ce987e7f3..f80799d5504 100644 --- a/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart +++ b/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart @@ -142,7 +142,7 @@ void main(List args) async { }, // TODO(matanlurey): Debug why flutter build apk often timesout. // See https://github.com/flutter/flutter/issues/158560 for details. - skip: buildCommand == 'apk' ? 'flutter build apk times out' : false, + skip: buildCommand == 'apk' ? 'flutter build apk times out' : false, // Temporary workaround for https://github.com/flutter/flutter/issues/158560. ); } From 1a31e396dbd99c426c6da56576b9a4c44c08bc8b Mon Sep 17 00:00:00 2001 From: Srivats Venkataraman <42980667+srivats22@users.noreply.github.com> Date: Wed, 13 Nov 2024 18:34:08 -0500 Subject: [PATCH 058/386] #154792 - CupertinoActionSheetAction cursor doesn't change to clickable on desktop (#158470) This PR is for issue #154792 The Video recording shows the before and after The first button with the text "Go" uses the default cursor The second button with the text "With Cursor" uses a custom cursor that has been passed in the parameters https://github.com/user-attachments/assets/e82ecd42-42b1-42c9-aa30-a6f3daddb436 Here is the code for the second button ```dart CupertinoButton( onPressed: () { showCupertinoModalPopup( context: context, builder: (BuildContext context) { return CupertinoActionSheet( title: const Text('The title'), message: const Text('Message'), actions: [ CupertinoActionSheetAction( cursor: SystemMouseCursors.forbidden, child: const Text('One'), onPressed: () {}, ), ], ); }, ); }, child: const Text('With Cursor'), ), ``` Fixes https://github.com/flutter/flutter/issues/154792 --- .../flutter/lib/src/cupertino/dialog.dart | 9 ++++- .../test/cupertino/action_sheet_test.dart | 38 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/packages/flutter/lib/src/cupertino/dialog.dart b/packages/flutter/lib/src/cupertino/dialog.dart index 38151897c9c..c264683d081 100644 --- a/packages/flutter/lib/src/cupertino/dialog.dart +++ b/packages/flutter/lib/src/cupertino/dialog.dart @@ -1215,6 +1215,7 @@ class CupertinoActionSheetAction extends StatefulWidget { required this.onPressed, this.isDefaultAction = false, this.isDestructiveAction = false, + this.mouseCursor, required this.child, }); @@ -1234,6 +1235,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 +1319,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/test/cupertino/action_sheet_test.dart b/packages/flutter/test/cupertino/action_sheet_test.dart index e8c4daf212d..0e0186cfc90 100644 --- a/packages/flutter/test/cupertino/action_sheet_test.dart +++ b/packages/flutter/test/cupertino/action_sheet_test.dart @@ -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; From 5f0f18d739c4383eb23ad9ece78fef1257a5b5a2 Mon Sep 17 00:00:00 2001 From: hgraceb <38378650+hgraceb@users.noreply.github.com> Date: Thu, 14 Nov 2024 08:08:22 +0800 Subject: [PATCH 059/386] Fix update order of SliverAppBar (#158159) Fixes #158158 Similar to 154484, but addressing more fundamental causes. We should call the child's `didUpdateWidget` before the child's `build` when states change. 1. Remove redundant code but keep the old test because we don't need it after this fix. 2. Add getters of `lastShrinkOffset` and `lastOverlapsContent` that are needed when `SliverAppBar.update`. 3. Add a test with a custom TabBar to avoid breaking when some changes to the default TabBar. --- packages/flutter/lib/src/material/tabs.dart | 8 ++-- .../rendering/sliver_persistent_header.dart | 6 +++ .../src/widgets/sliver_persistent_header.dart | 23 ++++----- .../test/material/app_bar_sliver_test.dart | 47 +++++++++++++++++++ 4 files changed, 68 insertions(+), 16 deletions(-) diff --git a/packages/flutter/lib/src/material/tabs.dart b/packages/flutter/lib/src/material/tabs.dart index dc8c9f03f9e..f3bff2e3789 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)); 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/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/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 From dec763979c54bc7b138100e4852c9a407be39b54 Mon Sep 17 00:00:00 2001 From: Mairramer <50643541+Mairramer@users.noreply.github.com> Date: Wed, 13 Nov 2024 21:10:14 -0300 Subject: [PATCH 060/386] Adjusts the Hindi TimeOfDayFormat to display in a LTR orientation in localizations. (#157998) Fixes https://github.com/flutter/flutter/issues/156565 This update corrects the `TimeOfDayFormat` mapping for the Hindi language. Previously, the format was incorrectly set to `a_space_h_colon_mm` - (a h:mm), but it should be `h_colon_mm_space_a` - (h:mm a) since Hindi is a LTR language. --- .../generated_material_localizations.dart | 2 +- .../lib/src/l10n/material_hi.arb | 2 +- .../test/material/time_picker_test.dart | 37 +++++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) 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/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')); From cc6ee0cc324473847bf475a77b08a54ccde2de8a Mon Sep 17 00:00:00 2001 From: Rexios Date: Wed, 13 Nov 2024 20:19:09 -0500 Subject: [PATCH 061/386] Add constraint options to `SearchAnchor` suggestions builder (#148856) Refactors the `SearchAnchor` suggestions builder to not take up the whole screen https://github.com/flutter/flutter/issues/148852 --- .../lib/search_view_template.dart | 3 + .../lib/src/material/search_anchor.dart | 156 +++++++++++------- .../lib/src/material/search_view_theme.dart | 10 ++ .../test/material/search_anchor_test.dart | 117 ++++++++++--- .../test/material/search_view_theme_test.dart | 10 +- 5 files changed, 212 insertions(+), 84 deletions(-) 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/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/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); From 9ac9049d0980d0df3a26108535021582d1565dbd Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Wed, 13 Nov 2024 18:12:14 -0800 Subject: [PATCH 062/386] Try with `bringup: true` debugging why `flutter build apk` often times out. (#158895) It would be nice to have somewhere to iterate and experiment with what we can do to either fix frequent timeout problems we have with `flutter build apk` (across platforms, to be clear, though I've just started with Linux) or get more information on why the crashes/timeouts happen. Open to other ways to doing this (though preferably _not_ LED). --- .ci.yaml | 23 +++++ TESTOWNERS | 1 + dev/bots/test.dart | 15 ++++ .../test/flutter_build_apk.shard/README.md | 3 + .../flutter_build_apk_test.dart | 87 +++++++++++++++++++ 5 files changed, 129 insertions(+) create mode 100644 packages/flutter_tools/test/flutter_build_apk.shard/README.md create mode 100644 packages/flutter_tools/test/flutter_build_apk.shard/flutter_build_apk_test.dart diff --git a/.ci.yaml b/.ci.yaml index da9363eecd4..873c01617f2 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -1330,6 +1330,29 @@ targets: - bin/** - .ci.yaml + - name: Linux flutter_build_apk_health_tests + recipe: flutter/flutter_drone + # WARNING: Do *NOT* enable. This intended for testing on CI only. + # Ask matanlurey@ or @gmackall if you have any questions. + bringup: true + timeout: 60 + properties: + add_recipes_cq: "true" + dependencies: >- + [ + {"dependency": "android_sdk", "version": "version:35v1"}, + {"dependency": "chrome_and_driver", "version": "version:125.0.6422.141"}, + {"dependency": "clang", "version": "git_revision:5d5aba78dbbee75508f01bcaa69aedb2ab79065a"}, + {"dependency": "cmake", "version": "build_id:8787856497187628321"}, + {"dependency": "goldctl", "version": "git_revision:2387d6fff449587eecbb7e45b2692ca0710b63b9"}, + {"dependency": "ninja", "version": "version:1.9.0"}, + {"dependency": "open_jdk", "version": "version:17"} + ] + shard: flutter_build_apk_health_tests + tags: > + ["framework", "hostonly", "shard", "linux"] + test_timeout_secs: "2700" + - name: Linux android_preview_tool_integration_tests recipe: flutter/flutter_drone timeout: 60 diff --git a/TESTOWNERS b/TESTOWNERS index 349b34c3b40..57a180a3e26 100644 --- a/TESTOWNERS +++ b/TESTOWNERS @@ -329,6 +329,7 @@ # coverage @goderbauer @flutter/infra # customer_testing @Piinks @flutter/framework # docs @Piinks @flutter/framework +# flutter_build_apk_health_tests @matanlurey @gmackall # flutter_driver_android_test @matanlurey @johnmccutchan # flutter_packaging @christopherfujino @flutter/infra # flutter_plugins @stuartmorgan @flutter/plugin diff --git a/dev/bots/test.dart b/dev/bots/test.dart index 3b8a17c0a78..7073a9f3b03 100644 --- a/dev/bots/test.dart +++ b/dev/bots/test.dart @@ -132,6 +132,7 @@ Future main(List args) async { 'tool_tests': _runToolTests, 'web_tool_tests': _runWebToolTests, 'tool_integration_tests': _runIntegrationToolTests, + 'flutter_build_apk_health_tests': _runFlutterBuildApkHealthTests, 'android_preview_tool_integration_tests': androidPreviewIntegrationToolTestsRunner, 'android_java11_tool_integration_tests': androidJava11IntegrationToolTestsRunner, 'tool_host_cross_arch_tests': _runToolHostCrossArchTests, @@ -234,6 +235,20 @@ Future _runIntegrationToolTests() async { ); } +Future _runFlutterBuildApkHealthTests() async { + final List allTests = Directory(path.join(_toolsPath, 'test', 'flutter_build_apk.shard')) + .listSync(recursive: true).whereType() + .map((FileSystemEntity entry) => path.relative(entry.path, from: _toolsPath)) + .where((String testPath) => path.basename(testPath).endsWith('_test.dart')).toList(); + + await runDartTest( + _toolsPath, + forceSingleCore: true, + testPaths: selectIndexOfTotalSubshard(allTests), + collectMetrics: true, + ); +} + Future _runToolTests() async { await selectSubshard({ 'general': _runGeneralToolTests, diff --git a/packages/flutter_tools/test/flutter_build_apk.shard/README.md b/packages/flutter_tools/test/flutter_build_apk.shard/README.md new file mode 100644 index 00000000000..d5d85c11f4b --- /dev/null +++ b/packages/flutter_tools/test/flutter_build_apk.shard/README.md @@ -0,0 +1,3 @@ +# `flutter_build_apk.shard` + +Integration tests that debug why `flutter build apk` sometimes stalls on CI. diff --git a/packages/flutter_tools/test/flutter_build_apk.shard/flutter_build_apk_test.dart b/packages/flutter_tools/test/flutter_build_apk.shard/flutter_build_apk_test.dart new file mode 100644 index 00000000000..8a72d191c7f --- /dev/null +++ b/packages/flutter_tools/test/flutter_build_apk.shard/flutter_build_apk_test.dart @@ -0,0 +1,87 @@ +// 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:file/file.dart'; + +import '../integration.shard/test_utils.dart'; +import '../src/common.dart'; + +void main() { + final String flutterRoot = getFlutterRoot(); + final String flutterBin = fileSystem.path.join(flutterRoot, 'bin', 'flutter'); + + late Directory tmpDir; + + setUp(() { + tmpDir = fileSystem.systemTempDirectory.createTempSync(); + }); + + tearDown(() { + tryToDelete(tmpDir); + }); + + Future setGradleLoggingLevel( + String level, { + required Directory projectDir, + }) async { + // Open gradle.properties and append to it. + final Directory androidDir = projectDir.childDirectory('android'); + final File gradleDotProperties = androidDir.childFile('gradle.properties'); + final io.IOSink sink = gradleDotProperties.openWrite(mode: FileMode.append); + + sink.writeln('org.gradle.logging.level=$level'); + await sink.flush(); + await sink.close(); + + // For debugging, print the current output. + io.stderr.writeln('${gradleDotProperties.path}:'); + io.stderr.writeln(gradleDotProperties.readAsStringSync()); + } + + // Normally these tests should take about a minute, but sometimes for + // unknown reasons they can take 30m+ and timeout. The intent behind this loop + // is to get more information on what exactly is happening. + for (int i = 1; i <= 10; i++) { + test('flutter build apk | attempt $i of 10', () async { + final String package = 'flutter_build_apk_test_$i'; + + // Create a new Flutter app. + await expectLater( + processManager.run( + [ + flutterBin, + 'create', + package, + ], + workingDirectory: tmpDir.path, + ), + completion(const ProcessResultMatcher()), + reason: 'Should create a new blank Flutter project', + ); + + // Tweak verbosity of just gradle. + final Directory projectDir = tmpDir.childDirectory(package); + await setGradleLoggingLevel('debug', projectDir: projectDir); + + // Build the APK. + final List args = [ + flutterBin, + '--verbose', + 'build', + 'apk', + '--debug', + ]; + io.stderr.writeln('Running $args...'); + + final io.Process process = await processManager.start( + args, + workingDirectory: projectDir.path, + mode: io.ProcessStartMode.inheritStdio, + ); + await expectLater(process.exitCode, completion(0)); + }); + } +} From 125b4e945e7e9d8bbbd9276b1a2d9162bd09696a Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Wed, 13 Nov 2024 18:33:34 -0800 Subject: [PATCH 063/386] Move explicit package dependencies to a feature flag (#158016) Closes https://github.com/flutter/flutter/issues/158012. This is (effectively) a user-facing NOP, which is exchanging an on-by-default command-line argument (`--implicit-pubspec-resolution`) for an off-by-default global feature flag (`explicit-package-dependencies`). It matches the mental model better, is less painstaking to maintain and feed throughout, and will be easier to globally flip on/off in a future PR. --------- Co-authored-by: Andrew Kolos --- .../lib/src/build_system/build_system.dart | 9 -- .../build_system/targets/localizations.dart | 3 +- .../flutter_tools/lib/src/bundle_builder.dart | 2 - .../lib/src/commands/assemble.dart | 2 - .../lib/src/commands/attach.dart | 6 - .../lib/src/commands/build_bundle.dart | 2 - .../lib/src/commands/build_ios_framework.dart | 2 - .../src/commands/build_macos_framework.dart | 2 - .../lib/src/commands/build_web.dart | 2 - .../lib/src/commands/create.dart | 2 - .../lib/src/commands/create_base.dart | 2 - .../lib/src/commands/custom_devices.dart | 1 - .../lib/src/commands/daemon.dart | 21 +--- .../flutter_tools/lib/src/commands/drive.dart | 2 - .../lib/src/commands/packages.dart | 14 +-- .../flutter_tools/lib/src/commands/run.dart | 6 - .../flutter_tools/lib/src/context_runner.dart | 2 - .../lib/src/custom_devices/custom_device.dart | 8 -- .../src/dart/generate_synthetic_packages.dart | 13 +- .../lib/src/drive/drive_service.dart | 6 +- .../lib/src/drive/web_driver_service.dart | 6 +- packages/flutter_tools/lib/src/features.dart | 28 +++++ .../lib/src/flutter_device_manager.dart | 4 - .../lib/src/flutter_features.dart | 3 + .../lib/src/flutter_plugins.dart | 41 ++----- packages/flutter_tools/lib/src/ios/mac.dart | 2 +- .../lib/src/isolated/resident_web_runner.dart | 8 -- .../lib/src/macos/cocoapod_utils.dart | 3 +- .../flutter_tools/lib/src/preview_device.dart | 8 -- packages/flutter_tools/lib/src/project.dart | 5 - .../lib/src/resident_runner.dart | 4 - packages/flutter_tools/lib/src/run_cold.dart | 1 - packages/flutter_tools/lib/src/run_hot.dart | 1 - .../lib/src/runner/flutter_command.dart | 2 - .../lib/src/tester/flutter_tester.dart | 6 - .../flutter_tools/lib/src/web/compile.dart | 112 +++++++++++------- .../flutter_tools/lib/src/web/web_runner.dart | 1 - .../commands.shard/hermetic/attach_test.dart | 1 - .../commands.shard/hermetic/daemon_test.dart | 33 ------ .../hermetic/generate_localizations_test.dart | 2 +- .../hermetic/proxied_devices_test.dart | 5 - .../commands.shard/hermetic/run_test.dart | 4 +- .../permeable/build_bundle_test.dart | 1 - .../permeable/packages_test.dart | 8 +- .../general.shard/bundle_builder_test.dart | 3 - .../test/general.shard/cold_test.dart | 5 - .../general.shard/commands/daemon_test.dart | 2 - .../custom_devices/custom_device_test.dart | 16 --- .../generate_synthetic_packages_test.dart | 38 +++--- .../drive/web_driver_service_test.dart | 2 - .../test/general.shard/hot_test.dart | 10 -- .../test/general.shard/isolated/hot_test.dart | 2 - .../isolated/resident_runner_test.dart | 1 - .../general.shard/macos/cocoapods_test.dart | 2 +- .../test/general.shard/plugins_test.dart | 84 ++++++------- .../general.shard/preview_device_test.dart | 7 -- .../test/general.shard/project_test.dart | 30 ++--- .../general.shard/resident_runner_test.dart | 32 ----- .../resident_web_runner_cold_test.dart | 5 - .../resident_web_runner_test.dart | 11 -- .../tester/flutter_tester_test.dart | 2 - .../general.shard/web/compile_web_test.dart | 2 - packages/flutter_tools/test/src/fakes.dart | 5 + packages/flutter_tools/test/src/testbed.dart | 4 +- .../web.shard/web_driver_service_test.dart | 1 - 65 files changed, 224 insertions(+), 436 deletions(-) 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..0fd777ab22d 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]. @@ -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/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/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..1f2de226563 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; } diff --git a/packages/flutter_tools/lib/src/commands/attach.dart b/packages/flutter_tools/lib/src/commands/attach.dart index 84cb841fc95..2ad5dc1632f 100644 --- a/packages/flutter_tools/lib/src/commands/attach.dart +++ b/packages/flutter_tools/lib/src/commands/attach.dart @@ -279,7 +279,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; @@ -466,7 +465,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, @@ -479,13 +477,11 @@ known, it can be explicitly provided to attach via the command-line, e.g. nativeAssetsYamlFile: stringArg(FlutterOptions.kNativeAssetsYamlFile), nativeAssetsBuilder: _nativeAssetsBuilder, analytics: analytics, - useImplicitPubspecResolution: useImplicitPubspecResolution, ) : ColdRunner( flutterDevices, target: targetFile, debuggingOptions: debuggingOptions, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); } @@ -512,7 +508,6 @@ class HotRunnerFactory { FlutterProject? flutterProject, String? nativeAssetsYamlFile, required HotRunnerNativeAssetsBuilder? nativeAssetsBuilder, - required bool useImplicitPubspecResolution, required Analytics analytics, }) => HotRunner( devices, @@ -527,6 +522,5 @@ class HotRunnerFactory { nativeAssetsYamlFile: nativeAssetsYamlFile, nativeAssetsBuilder: nativeAssetsBuilder, analytics: analytics, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); } 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_framework.dart b/packages/flutter_tools/lib/src/commands/build_ios_framework.dart index 3398ba78aa8..fc424ca9e12 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'; @@ -461,7 +460,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..7794b72860b 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'; @@ -240,7 +239,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..f0c2e4e2ccd 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'; @@ -227,7 +226,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/create.dart b/packages/flutter_tools/lib/src/commands/create.dart index 39386f45c64..761202e629e 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 = @@ -459,7 +458,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..76ff09a32b2 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 = [ @@ -575,7 +574,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..6749b988fea 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(); @@ -717,7 +705,6 @@ class AppDomain extends Domain { systemClock: globals.systemClock, logger: globals.logger, fileSystem: globals.fs, - useImplicitPubspecResolution: _useImplicitPubspecResolution, ); } else if (enableHotReload) { runner = HotRunner( @@ -731,7 +718,6 @@ class AppDomain extends Domain { machine: machine, analytics: globals.analytics, nativeAssetsBuilder: nativeAssetsBuilder, - useImplicitPubspecResolution: _useImplicitPubspecResolution, ); } else { runner = ColdRunner( @@ -740,7 +726,6 @@ class AppDomain extends Domain { debuggingOptions: options, applicationBinary: applicationBinary, machine: machine, - useImplicitPubspecResolution: _useImplicitPubspecResolution, ); } 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 db44e62c94e..4b9cb710bf1 100644 --- a/packages/flutter_tools/lib/src/commands/run.dart +++ b/packages/flutter_tools/lib/src/commands/run.dart @@ -681,7 +681,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,7 +696,6 @@ class RunCommand extends RunCommandBase { analytics: globals.analytics, nativeAssetsYamlFile: stringArg(FlutterOptions.kNativeAssetsYamlFile), nativeAssetsBuilder: _nativeAssetsBuilder, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); } else if (webMode) { return webRunnerFactory!.createWebRunner( @@ -711,7 +709,6 @@ class RunCommand extends RunCommandBase { analytics: globals.analytics, logger: globals.logger, systemClock: globals.systemClock, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); } return ColdRunner( @@ -724,13 +721,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), @@ -740,7 +735,6 @@ class RunCommand extends RunCommandBase { ? globals.logger as NotifyingLogger : NotifyingLogger(verbose: globals.logger.isVerbose, parent: globals.logger), logToStdout: true, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); return daemon; } 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..4de1502151e 100644 --- a/packages/flutter_tools/lib/src/custom_devices/custom_device.dart +++ b/packages/flutter_tools/lib/src/custom_devices/custom_device.dart @@ -440,10 +440,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 +469,6 @@ class CustomDevice extends Device { final ProcessUtils _processUtils; final Map _sessions = {}; final CustomDeviceLogReader _globalLogReader; - final bool _useImplicitPubspecResolution; @override final DevicePortForwarder portForwarder; @@ -765,7 +762,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 +823,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 +852,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..066cab28fd0 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 defualt. 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/drive/drive_service.dart b/packages/flutter_tools/lib/src/drive/drive_service.dart index b260a031073..bf6ccb6f017 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( 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..8958a4150b7 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; @@ -97,7 +94,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..4e91d0abb63 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. @@ -193,6 +197,30 @@ const Feature swiftPackageManager = Feature( ), ); +/// 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, + ), + beta: FeatureChannelSetting( + available: true, + ), + stable: FeatureChannelSetting( + available: true, + ), +); + /// A [Feature] is a process for conditionally enabling tool features. /// /// All settings are optional, and if not provided will generally default to 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_plugins.dart b/packages/flutter_tools/lib/src/flutter_plugins.dart index fcd45e26d86..5bed044b59e 100644 --- a/packages/flutter_tools/lib/src/flutter_plugins.dart +++ b/packages/flutter_tools/lib/src/flutter_plugins.dart @@ -89,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); @@ -122,10 +105,7 @@ 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( @@ -1062,14 +1042,16 @@ 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; @@ -1119,7 +1101,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); } @@ -1138,7 +1120,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, @@ -1147,7 +1128,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) { @@ -1575,7 +1556,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/mac.dart b/packages/flutter_tools/lib/src/ios/mac.dart index 06be3d76ff0..e634f8dc20a 100644 --- a/packages/flutter_tools/lib/src/ios/mac.dart +++ b/packages/flutter_tools/lib/src/ios/mac.dart @@ -938,7 +938,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/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/macos/cocoapod_utils.dart b/packages/flutter_tools/lib/src/macos/cocoapod_utils.dart index 007d6206c88..9226778e6b9 100644 --- a/packages/flutter_tools/lib/src/macos/cocoapod_utils.dart +++ b/packages/flutter_tools/lib/src/macos/cocoapod_utils.dart @@ -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 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 12e10760835..d222e273a25 100644 --- a/packages/flutter_tools/lib/src/project.dart +++ b/packages/flutter_tools/lib/src/project.dart @@ -321,7 +321,6 @@ class FlutterProject { Future regeneratePlatformSpecificTooling({ DeprecationBehavior deprecationBehavior = DeprecationBehavior.none, Iterable? allowedPlugins, - required bool useImplicitPubspecResolution, }) async { return ensureReadyForPlatformSpecificTooling( androidPlatform: android.existsSync(), @@ -334,7 +333,6 @@ class FlutterProject { webPlatform: featureFlags.isWebEnabled && web.existsSync(), deprecationBehavior: deprecationBehavior, allowedPlugins: allowedPlugins, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); } @@ -349,7 +347,6 @@ class FlutterProject { bool webPlatform = false, DeprecationBehavior deprecationBehavior = DeprecationBehavior.none, Iterable? allowedPlugins, - required bool useImplicitPubspecResolution, }) async { if (!directory.existsSync() || isPlugin) { return; @@ -358,7 +355,6 @@ class FlutterProject { this, iosPlatform: iosPlatform, macOSPlatform: macOSPlatform, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); if (androidPlatform) { await android.ensureReadyForPlatformSpecificTooling(deprecationBehavior: deprecationBehavior); @@ -386,7 +382,6 @@ class FlutterProject { macOSPlatform: macOSPlatform, windowsPlatform: windowsPlatform, allowedPlugins: allowedPlugins, - useImplicitPubspecResolution: useImplicitPubspecResolution, ); } diff --git a/packages/flutter_tools/lib/src/resident_runner.dart b/packages/flutter_tools/lib/src/resident_runner.dart index b88ba4b1664..af8aabbea5d 100644 --- a/packages/flutter_tools/lib/src/resident_runner.dart +++ b/packages/flutter_tools/lib/src/resident_runner.dart @@ -1053,7 +1053,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 +1063,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 +1095,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; @@ -1224,7 +1221,6 @@ abstract class ResidentRunner extends ResidentHandlers { // Needed for Dart plugin registry generation. kTargetFile: mainPath, }, - useImplicitPubspecResolution: _useImplicitPubspecResolution, ); final CompositeTarget compositeTarget = CompositeTarget([ diff --git a/packages/flutter_tools/lib/src/run_cold.dart b/packages/flutter_tools/lib/src/run_cold.dart index b07ee54dbb1..55e699cdc14 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, diff --git a/packages/flutter_tools/lib/src/run_hot.dart b/packages/flutter_tools/lib/src/run_hot.dart index 733c7c8ec5b..dc27fd0bf37 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, diff --git a/packages/flutter_tools/lib/src/runner/flutter_command.dart b/packages/flutter_tools/lib/src/runner/flutter_command.dart index 44b573a112e..102d500e38a 100644 --- a/packages/flutter_tools/lib/src/runner/flutter_command.dart +++ b/packages/flutter_tools/lib/src/runner/flutter_command.dart @@ -1770,7 +1770,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 +1792,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/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/web/compile.dart b/packages/flutter_tools/lib/src/web/compile.dart index 5928479a642..466596ce5b9 100644 --- a/packages/flutter_tools/lib/src/web/compile.dart +++ b/packages/flutter_tools/lib/src/web/compile.dart @@ -46,15 +46,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 +61,6 @@ class WebBuilder { final Analytics _analytics; final FlutterVersion _flutterVersion; final FileSystem _fileSystem; - final bool _useImplicitPubspecResolution; Future buildWeb( FlutterProject flutterProject, @@ -74,8 +71,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 +86,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 +95,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 +114,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 +163,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, @@ -189,7 +192,8 @@ enum WebRendererMode implements CliEnum { /// Always use skwasm. skwasm; - factory WebRendererMode.fromCliOption(String? webRendererString, {required bool useWasm}) { + factory WebRendererMode.fromCliOption(String? webRendererString, + {required bool useWasm}) { if (webRendererString == null) { return getDefault(useWasm: useWasm); } @@ -215,8 +219,8 @@ 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. Do not use "--web-renderer=$name".' + '\nSee: https://docs.flutter.dev/to/web-html-renderer-deprecation'; @override String get cliName => kebabCase(name); @@ -253,9 +257,11 @@ enum WebRendererMode implements CliEnum { 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=')); + 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); return dartDefinesSet.toList(); @@ -264,16 +270,19 @@ enum WebRendererMode implements CliEnum { /// 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 +290,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/test/commands.shard/hermetic/attach_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/attach_test.dart index 175239ea501..31ce4464493 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/attach_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/attach_test.dart @@ -1259,7 +1259,6 @@ class FakeHotRunnerFactory extends Fake implements HotRunnerFactory { 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/daemon_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/daemon_test.dart index 11922609f57..4e62f13b903 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}})); 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..3572f24e3cd 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(''' 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..35468443cbb 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(); 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 ae038dd3ffa..1474fe995d9 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/run_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/run_test.dart @@ -1583,14 +1583,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; 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..0cba55056ea 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 @@ -544,6 +544,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/packages_test.dart b/packages/flutter_tools/test/commands.shard/permeable/packages_test.dart index 31101526e14..86522c56129 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'; @@ -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/general.shard/bundle_builder_test.dart b/packages/flutter_tools/test/general.shard/bundle_builder_test.dart index 29618bd22e8..a9c9ad40663 100644 --- a/packages/flutter_tools/test/general.shard/bundle_builder_test.dart +++ b/packages/flutter_tools/test/general.shard/bundle_builder_test.dart @@ -48,7 +48,6 @@ void main() { assetDirPath: 'example', depfilePath: 'example.d', buildSystem: buildSystem, - useImplicitPubspecResolution: true, ); expect(globals.fs.file(globals.fs.path.join('example', 'kernel_blob.bin')).existsSync(), true); expect(globals.fs.file(globals.fs.path.join('example', 'LICENSE')).existsSync(), true); @@ -138,7 +137,6 @@ void main() { assetDirPath: 'example', depfilePath: 'example.d', buildSystem: TestBuildSystem.all(BuildResult(success: false)), - useImplicitPubspecResolution: true, ), throwsToolExit() ); @@ -184,7 +182,6 @@ void main() { assetDirPath: assetDirPath, depfilePath: depfilePath, buildSystem: buildSystem, - useImplicitPubspecResolution: true, ); expect(env, isNotNull); diff --git a/packages/flutter_tools/test/general.shard/cold_test.dart b/packages/flutter_tools/test/general.shard/cold_test.dart index ceaa0353125..51521645e4f 100644 --- a/packages/flutter_tools/test/general.shard/cold_test.dart +++ b/packages/flutter_tools/test/general.shard/cold_test.dart @@ -42,7 +42,6 @@ void main() { final int exitCode = await ColdRunner(devices, debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), target: 'main.dart', - useImplicitPubspecResolution: true, ).attach(); expect(exitCode, 2); }); @@ -59,7 +58,6 @@ void main() { await ColdRunner(devices, debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), target: 'main.dart', - useImplicitPubspecResolution: true, ).cleanupAtFinish(); expect(flutterDevice1.stopEchoingDeviceLogCount, 1); @@ -89,7 +87,6 @@ void main() { applicationBinary: applicationBinary, debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), target: 'main.dart', - useImplicitPubspecResolution: true, ).run(); expect(result, 1); @@ -106,7 +103,6 @@ void main() { debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), target: 'main.dart', traceStartup: true, - useImplicitPubspecResolution: true, ).run(); expect(result, 0); @@ -130,7 +126,6 @@ void main() { debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), target: 'main.dart', traceStartup: true, - useImplicitPubspecResolution: true, ).run(); expect(result, 0); diff --git a/packages/flutter_tools/test/general.shard/commands/daemon_test.dart b/packages/flutter_tools/test/general.shard/commands/daemon_test.dart index b2240362d86..b294e6cb9fb 100644 --- a/packages/flutter_tools/test/general.shard/commands/daemon_test.dart +++ b/packages/flutter_tools/test/general.shard/commands/daemon_test.dart @@ -29,7 +29,6 @@ void main() { bindPorts.add(port); return socket; }, - useImplicitPubspecResolution: true, ); await server.run(); expect(bindCalledTimes, 1); @@ -57,7 +56,6 @@ void main() { } return socket; }, - useImplicitPubspecResolution: true, ); await server.run(); expect(bindCalledTimes, 2); diff --git a/packages/flutter_tools/test/general.shard/custom_devices/custom_device_test.dart b/packages/flutter_tools/test/general.shard/custom_devices/custom_device_test.dart index 9dc78fdaf6a..67f2a5d4846 100644 --- a/packages/flutter_tools/test/general.shard/custom_devices/custom_device_test.dart +++ b/packages/flutter_tools/test/general.shard/custom_devices/custom_device_test.dart @@ -123,7 +123,6 @@ void main() { config: testConfig, processManager: FakeProcessManager.any(), logger: BufferLogger.test(), - useImplicitPubspecResolution: true, ); final PrebuiltLinuxApp linuxApp = PrebuiltLinuxApp(executable: 'foo'); @@ -167,7 +166,6 @@ void main() { directory: dir, logger: BufferLogger.test() ), - useImplicitPubspecResolution: true, ).devices(), []); }); @@ -186,7 +184,6 @@ void main() { directory: dir, logger: BufferLogger.test() ), - useImplicitPubspecResolution: true, ).devices(), []); }); @@ -211,7 +208,6 @@ void main() { directory: dir, logger: BufferLogger.test() ), - useImplicitPubspecResolution: true, ).devices(), hasLength(1) ); @@ -240,7 +236,6 @@ void main() { directory: dir, logger: BufferLogger.test(), ), - useImplicitPubspecResolution: true, ); final List discoveredDevices = await discovery.discoverDevices(); @@ -270,7 +265,6 @@ void main() { directory: dir, logger: BufferLogger.test(), ), - useImplicitPubspecResolution: true, ); expect(await discovery.discoverDevices(), hasLength(0)); @@ -295,7 +289,6 @@ void main() { directory: dir, logger: BufferLogger.test(), ), - useImplicitPubspecResolution: true, ); expect(await discovery.discoverDevices(), hasLength(0)); @@ -315,7 +308,6 @@ void main() { config: testConfig, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), - useImplicitPubspecResolution: true, ).isSupportedForProject(flutterProject), true); }); @@ -331,7 +323,6 @@ void main() { FakeCommand(command: testConfig.uninstallCommand), FakeCommand(command: testConfig.installCommand, onRun: (_) => bothCommandsWereExecuted = true), ]), - useImplicitPubspecResolution: true, ); expect(await device.installApp(PrebuiltLinuxApp(executable: 'exe')), true); @@ -394,7 +385,6 @@ void main() { config: testConfig, logger: BufferLogger.test(), processManager: processManager, - useImplicitPubspecResolution: true, ), appPackage: PrebuiltLinuxApp(executable: 'testexecutable'), logger: BufferLogger.test(), @@ -432,7 +422,6 @@ void main() { config: testConfigNonForwarding, logger: BufferLogger.test(), processManager: processManager, - useImplicitPubspecResolution: true, ), appPackage: PrebuiltLinuxApp(executable: 'testexecutable'), logger: BufferLogger.test(), @@ -498,7 +487,6 @@ void main() { directory: configFileDir, logger: BufferLogger.test() ), - useImplicitPubspecResolution: true, ); final List devices = await customDevices.discoverDevices(); @@ -548,7 +536,6 @@ void main() { config: testConfig, logger: BufferLogger.test(), processManager: processManager, - useImplicitPubspecResolution: true, ); expect(device.supportsScreenshot, true); @@ -577,7 +564,6 @@ void main() { ), logger: BufferLogger.test(), processManager: processManager, - useImplicitPubspecResolution: true, ); expect(device.supportsScreenshot, false); @@ -596,7 +582,6 @@ void main() { ), logger: BufferLogger.test(), processManager: FakeProcessManager.empty(), - useImplicitPubspecResolution: true, ); expect(await device.targetPlatform, TargetPlatform.linux_x64); @@ -664,7 +649,6 @@ class FakeBundleBuilder extends Fake implements BundleBuilder { String? assetDirPath, Uri? nativeAssets, bool buildNativeAssets = true, - required bool useImplicitPubspecResolution, @visibleForTesting BuildSystem? buildSystem }) async {} } diff --git a/packages/flutter_tools/test/general.shard/dart/generate_synthetic_packages_test.dart b/packages/flutter_tools/test/general.shard/dart/generate_synthetic_packages_test.dart index f29ca480209..e8d3c42ef0a 100644 --- a/packages/flutter_tools/test/general.shard/dart/generate_synthetic_packages_test.dart +++ b/packages/flutter_tools/test/general.shard/dart/generate_synthetic_packages_test.dart @@ -12,14 +12,16 @@ import 'package:flutter_tools/src/build_system/build_system.dart'; import 'package:flutter_tools/src/build_system/build_targets.dart'; import 'package:flutter_tools/src/build_system/targets/localizations.dart'; import 'package:flutter_tools/src/dart/generate_synthetic_packages.dart'; +import 'package:flutter_tools/src/features.dart'; import 'package:flutter_tools/src/isolated/build_targets.dart'; import '../../src/common.dart'; -import '../../src/fake_process_manager.dart'; +import '../../src/context.dart'; +import '../../src/fakes.dart'; import '../../src/test_build_system.dart'; void main() { - testWithoutContext('calls buildSystem.build with blank l10n.yaml file', () async { + testUsingContext('calls buildSystem.build with blank l10n.yaml file', () async { // Project directory setup for gen_l10n logic final MemoryFileSystem fileSystem = MemoryFileSystem.test(); @@ -68,7 +70,7 @@ void main() { await completer.future; }); - testWithoutContext('calls buildSystem.build with l10n.yaml synthetic-package: true', () async { + testUsingContext('calls buildSystem.build with l10n.yaml synthetic-package: true', () async { // Project directory setup for gen_l10n logic final MemoryFileSystem fileSystem = MemoryFileSystem.test(); @@ -118,7 +120,7 @@ void main() { await completer.future; }); - testWithoutContext('calls buildSystem.build with l10n.yaml synthetic-package: null', () async { + testUsingContext('calls buildSystem.build with l10n.yaml synthetic-package: null', () async { // Project directory setup for gen_l10n logic final MemoryFileSystem fileSystem = MemoryFileSystem.test(); @@ -166,7 +168,7 @@ void main() { await completer.future; }); - testWithoutContext('does not call buildSystem.build when l10n.yaml is not present', () async { + testUsingContext('does not call buildSystem.build when l10n.yaml is not present', () async { // Project directory setup for gen_l10n logic final MemoryFileSystem fileSystem = MemoryFileSystem.test(); @@ -196,7 +198,7 @@ void main() { ); }); - testWithoutContext('does not call buildSystem.build with incorrect l10n.yaml format', () async { + testUsingContext('does not call buildSystem.build with incorrect l10n.yaml format', () async { // Project directory setup for gen_l10n logic final MemoryFileSystem fileSystem = MemoryFileSystem.test(); @@ -232,7 +234,7 @@ void main() { ); }); - testWithoutContext('does not call buildSystem.build with non-bool "synthetic-package" value', () async { + testUsingContext('does not call buildSystem.build with non-bool "synthetic-package" value', () async { // Project directory setup for gen_l10n logic final MemoryFileSystem fileSystem = MemoryFileSystem.test(); @@ -268,7 +270,7 @@ void main() { ); }); - testWithoutContext('synthetic-package: true (implicit) logs a deprecation warning', () async { + testUsingContext('synthetic-package: true (implicit) logs a deprecation warning', () async { // Project directory setup for gen_l10n logic. final MemoryFileSystem fileSystem = MemoryFileSystem.test(); @@ -305,7 +307,7 @@ void main() { ); }); - testWithoutContext('synthetic-package: true (explicit) logs a deprecation warning', () async { + testUsingContext('synthetic-package: true (explicit) logs a deprecation warning', () async { // Project directory setup for gen_l10n logic. final MemoryFileSystem fileSystem = MemoryFileSystem.test(); @@ -340,7 +342,7 @@ void main() { ); }); - testWithoutContext('synthetic-package: false has no deprecation warning', () async { + testUsingContext('synthetic-package: false has no deprecation warning', () async { // Project directory setup for gen_l10n logic final MemoryFileSystem fileSystem = MemoryFileSystem.test(); @@ -375,7 +377,7 @@ void main() { ); }); - testWithoutContext('synthetic-package: true with --no-implicit-pubspec-resolution is an error', () async { + testUsingContext('synthetic-package: true with explicit-packages-resolution is an error', () async { // Project directory setup for gen_l10n logic final MemoryFileSystem fileSystem = MemoryFileSystem.test(); @@ -397,7 +399,6 @@ void main() { logger: mockBufferLogger, artifacts: Artifacts.test(), processManager: FakeProcessManager.any(), - useImplicitPubspecResolution: false, ); // Will throw if build is called. final TestBuildSystem buildSystem = TestBuildSystem.all(null); @@ -408,11 +409,15 @@ void main() { buildSystem: buildSystem, buildTargets: const NoOpBuildTargets(), ), - throwsToolExit(message: 'Cannot generate a synthetic package when --no-implicit-pubspec-resolution is passed'), + throwsToolExit(message: 'Cannot generate a synthetic package when explicit-package-dependencies is enabled'), ); + }, overrides: { + FeatureFlags: () => TestFeatureFlags( + isExplicitPackageDependenciesEnabled: true, + ), }); - testWithoutContext('synthetic-package defaults to false if --no-implicit-pubspec-resolution is passed', () async { + testUsingContext('synthetic-package defaults to false if explicit-package-dependencies is enabled', () async { // Project directory setup for gen_l10n logic final MemoryFileSystem fileSystem = MemoryFileSystem.test(); @@ -434,7 +439,6 @@ void main() { logger: mockBufferLogger, artifacts: Artifacts.test(), processManager: FakeProcessManager.any(), - useImplicitPubspecResolution: false, ); // Will throw if build is called. final TestBuildSystem buildSystem = TestBuildSystem.all(null); @@ -447,5 +451,9 @@ void main() { ), returnsNormally, ); + }, overrides: { + FeatureFlags: () => TestFeatureFlags( + isExplicitPackageDependenciesEnabled: true, + ), }); } diff --git a/packages/flutter_tools/test/general.shard/drive/web_driver_service_test.dart b/packages/flutter_tools/test/general.shard/drive/web_driver_service_test.dart index 840a872d7e2..8854e2c7a62 100644 --- a/packages/flutter_tools/test/general.shard/drive/web_driver_service_test.dart +++ b/packages/flutter_tools/test/general.shard/drive/web_driver_service_test.dart @@ -318,7 +318,6 @@ class FakeWebRunnerFactory implements WebRunnerFactory { Usage? usage, Analytics? analytics, bool machine = false, - required bool useImplicitPubspecResolution, }) { expect(stayResident, isTrue); return FakeResidentRunner( @@ -382,7 +381,6 @@ WebDriverService setUpDriverService() { processManager: FakeProcessManager.any(), ), dartSdkPath: 'dart', - useImplicitPubspecResolution: true, ); } diff --git a/packages/flutter_tools/test/general.shard/hot_test.dart b/packages/flutter_tools/test/general.shard/hot_test.dart index 6a2b4bad382..6e25dbab72b 100644 --- a/packages/flutter_tools/test/general.shard/hot_test.dart +++ b/packages/flutter_tools/test/general.shard/hot_test.dart @@ -149,7 +149,6 @@ void main() { debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), target: 'main.dart', devtoolsHandler: createNoOpHandler, - useImplicitPubspecResolution: true, analytics: fakeAnalytics, ).restart(fullRestart: true); expect(result.isOk, false); @@ -182,7 +181,6 @@ void main() { debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), target: 'main.dart', devtoolsHandler: createNoOpHandler, - useImplicitPubspecResolution: true, reassembleHelper: ( List flutterDevices, Map> viewCache, @@ -232,7 +230,6 @@ void main() { debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), target: 'main.dart', analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ).cleanupAfterSignal(); expect(shutdownTestingConfig.shutdownHookCalled, true); }, overrides: { @@ -261,7 +258,6 @@ void main() { debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), target: 'main.dart', analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ).preExit(); expect(shutdownTestingConfig.shutdownHookCalled, true); }, overrides: { @@ -312,7 +308,6 @@ void main() { devtoolsHandler: createNoOpHandler, stopwatchFactory: fakeStopwatchFactory, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ).restart(fullRestart: true); expect(result.isOk, true); @@ -400,7 +395,6 @@ void main() { devtoolsHandler: createNoOpHandler, stopwatchFactory: fakeStopwatchFactory, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, reloadSourcesHelper: ( HotRunner hotRunner, List flutterDevices, @@ -507,7 +501,6 @@ void main() { target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); await expectLater(runner.restart(fullRestart: true), throwsA(isA().having((Exception e) => e.toString(), 'message', 'Exception: updateDevFS failed'))); @@ -543,7 +536,6 @@ void main() { target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); await expectLater(runner.restart(), throwsA(isA().having((Exception e) => e.toString(), 'message', 'Exception: updateDevFS failed'))); @@ -597,7 +589,6 @@ void main() { debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), target: 'main.dart', analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ).attach(needsFullRestart: false); expect(exitCode, 2); }, overrides: { @@ -636,7 +627,6 @@ void main() { debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), target: 'main.dart', analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ).cleanupAtFinish(); expect(device1.disposed, true); diff --git a/packages/flutter_tools/test/general.shard/isolated/hot_test.dart b/packages/flutter_tools/test/general.shard/isolated/hot_test.dart index f1fe433f343..60ee84f6b0a 100644 --- a/packages/flutter_tools/test/general.shard/isolated/hot_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/hot_test.dart @@ -90,7 +90,6 @@ void main() { devtoolsHandler: createNoOpHandler, nativeAssetsBuilder: FakeHotRunnerNativeAssetsBuilder(buildRunner), analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); final OperationResult result = await hotRunner.restart(fullRestart: true); expect(result.isOk, true); @@ -161,7 +160,6 @@ void main() { devtoolsHandler: createNoOpHandler, nativeAssetsBuilder: FakeHotRunnerNativeAssetsBuilder(buildRunner), analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); expect( () => hotRunner.run(), diff --git a/packages/flutter_tools/test/general.shard/isolated/resident_runner_test.dart b/packages/flutter_tools/test/general.shard/isolated/resident_runner_test.dart index 45999bdd01c..aec25320856 100644 --- a/packages/flutter_tools/test/general.shard/isolated/resident_runner_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/resident_runner_test.dart @@ -74,7 +74,6 @@ void main() { nativeAssetsBuilder: FakeHotRunnerNativeAssetsBuilder(buildRunner), analytics: FakeAnalytics(), nativeAssetsYamlFile: 'foo.yaml', - useImplicitPubspecResolution: true, ); final int result = await residentRunner.run(); diff --git a/packages/flutter_tools/test/general.shard/macos/cocoapods_test.dart b/packages/flutter_tools/test/general.shard/macos/cocoapods_test.dart index 97c3899a3a5..1e2faf3613f 100644 --- a/packages/flutter_tools/test/general.shard/macos/cocoapods_test.dart +++ b/packages/flutter_tools/test/general.shard/macos/cocoapods_test.dart @@ -345,7 +345,7 @@ void main() { ..writeAsStringSync('Existing release config'); final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.directory('project')); - await injectPlugins(project, iosPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(project, iosPlatform: true); final String debugContents = projectUnderTest.ios.xcodeConfigFor('Debug').readAsStringSync(); expect(debugContents, contains( diff --git a/packages/flutter_tools/test/general.shard/plugins_test.dart b/packages/flutter_tools/test/general.shard/plugins_test.dart index 8c38156dbac..443d94980f9 100644 --- a/packages/flutter_tools/test/general.shard/plugins_test.dart +++ b/packages/flutter_tools/test/general.shard/plugins_test.dart @@ -404,7 +404,7 @@ dependencies: group('refreshPlugins', () { testUsingContext('Refreshing the plugin list is a no-op when the plugins list stays empty', () async { - await refreshPluginsList(flutterProject, useImplicitPubspecResolution: true); + await refreshPluginsList(flutterProject); expect(flutterProject.flutterPluginsFile.existsSync(), false); expect(flutterProject.flutterPluginsDependenciesFile.existsSync(), false); @@ -417,7 +417,7 @@ dependencies: flutterProject.flutterPluginsFile.createSync(); flutterProject.flutterPluginsDependenciesFile.createSync(); - await refreshPluginsList(flutterProject, useImplicitPubspecResolution: true); + await refreshPluginsList(flutterProject); expect(flutterProject.flutterPluginsFile.existsSync(), false); expect(flutterProject.flutterPluginsDependenciesFile.existsSync(), false); @@ -436,7 +436,7 @@ dependencies: iosProject.testExists = true; - await refreshPluginsList(flutterProject, useImplicitPubspecResolution: true); + await refreshPluginsList(flutterProject); expect(flutterProject.flutterPluginsFile.existsSync(), true); expect(flutterProject.flutterPluginsDependenciesFile.existsSync(), true); @@ -450,7 +450,7 @@ dependencies: ProcessManager: () => FakeProcessManager.any(), }); - testUsingContext('Opting out of useImplicitPubspecResolution omits .flutter-plugins', () async { + testUsingContext('Opting in to explicit-package-dependencies omits .flutter-plugins', () async { createFakePlugins(fs, [ 'plugin_d', 'plugin_a', @@ -458,11 +458,14 @@ dependencies: '/local_plugins/plugin_b', ]); - await refreshPluginsList(flutterProject, useImplicitPubspecResolution: false); + await refreshPluginsList(flutterProject); expect(flutterProject.flutterPluginsFile, isNot(exists)); expect(flutterProject.flutterPluginsDependenciesFile, exists); }, overrides: { + FeatureFlags: () => TestFeatureFlags( + isExplicitPackageDependenciesEnabled: true, + ), FileSystem: () => fs, ProcessManager: FakeProcessManager.empty, Pub: FakePubWithPrimedDeps.new, @@ -479,7 +482,7 @@ dependencies: final DateTime dateCreated = DateTime(1970); systemClock.currentTime = dateCreated; - await refreshPluginsList(flutterProject, useImplicitPubspecResolution: true); + await refreshPluginsList(flutterProject); // Verify .flutter-plugins-dependencies is configured correctly. expect(flutterProject.flutterPluginsFile.existsSync(), true); @@ -597,7 +600,7 @@ dependencies: final DateTime dateCreated = DateTime(1970); systemClock.currentTime = dateCreated; - await refreshPluginsList(flutterProject, useImplicitPubspecResolution: true); + await refreshPluginsList(flutterProject); expect(flutterProject.flutterPluginsDependenciesFile.existsSync(), true); final String pluginsString = flutterProject.flutterPluginsDependenciesFile.readAsStringSync(); @@ -674,7 +677,6 @@ dependencies: flutterProject, iosPlatform: true, macOSPlatform: true, - useImplicitPubspecResolution: true, ); expect(flutterProject.flutterPluginsDependenciesFile.existsSync(), true); @@ -720,7 +722,7 @@ dependencies: iosProject.usesSwiftPackageManager = true; macosProject.usesSwiftPackageManager = true; - await refreshPluginsList(flutterProject, forceCocoaPodsOnly: true, useImplicitPubspecResolution: true); + await refreshPluginsList(flutterProject, forceCocoaPodsOnly: true); expect(flutterProject.flutterPluginsDependenciesFile.existsSync(), true); final String pluginsString = flutterProject.flutterPluginsDependenciesFile @@ -768,7 +770,6 @@ dependencies: flutterProject, iosPlatform: true, macOSPlatform: true, - useImplicitPubspecResolution: true, ); expect(flutterProject.flutterPluginsDependenciesFile.existsSync(), true); @@ -798,7 +799,7 @@ dependencies: iosProject.testExists = true; macosProject.exists = true; - await refreshPluginsList(flutterProject, iosPlatform: true, macOSPlatform: true, useImplicitPubspecResolution: true); + await refreshPluginsList(flutterProject, iosPlatform: true, macOSPlatform: true); expect(iosProject.podManifestLock.existsSync(), false); expect(macosProject.podManifestLock.existsSync(), false); }, overrides: { @@ -817,11 +818,11 @@ dependencies: // Since there was no plugins list, the lock files will be invalidated. // The second call is where the plugins list is compared to the existing one, and if there is no change, // the podfiles shouldn't be invalidated. - await refreshPluginsList(flutterProject, iosPlatform: true, macOSPlatform: true, useImplicitPubspecResolution: true); + await refreshPluginsList(flutterProject, iosPlatform: true, macOSPlatform: true); simulatePodInstallRun(iosProject); simulatePodInstallRun(macosProject); - await refreshPluginsList(flutterProject, useImplicitPubspecResolution: true); + await refreshPluginsList(flutterProject); expect(iosProject.podManifestLock.existsSync(), true); expect(macosProject.podManifestLock.existsSync(), true); }, overrides: { @@ -842,7 +843,7 @@ dependencies: testUsingContext('Registrant uses new embedding if app uses new embedding', () async { androidProject.embeddingVersion = AndroidEmbeddingVersion.v2; - await injectPlugins(flutterProject, androidPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, androidPlatform: true); final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) @@ -865,7 +866,7 @@ dependencies: await expectLater( () async { - await injectPlugins(flutterProject, androidPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, androidPlatform: true); }, throwsToolExit( message: "The plugin `plugin1` doesn't have a main class defined in " @@ -887,7 +888,7 @@ dependencies: createDualSupportJavaPlugin4(); - await injectPlugins(flutterProject, androidPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, androidPlatform: true); final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) @@ -908,7 +909,7 @@ dependencies: flutterProject.isModule = true; androidProject.embeddingVersion = AndroidEmbeddingVersion.v2; - await injectPlugins(flutterProject, androidPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, androidPlatform: true); final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) @@ -929,7 +930,7 @@ dependencies: createNewJavaPlugin1(); - await injectPlugins(flutterProject, androidPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, androidPlatform: true); final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) @@ -950,7 +951,7 @@ dependencies: createDualSupportJavaPlugin4(); - await injectPlugins(flutterProject, androidPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, androidPlatform: true); final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) @@ -971,7 +972,7 @@ dependencies: createDualSupportJavaPlugin4(); - await injectPlugins(flutterProject, androidPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, androidPlatform: true); final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) @@ -989,7 +990,7 @@ dependencies: testUsingContext('Does not throw when AndroidManifest.xml is not found', () async { final File manifest = fs.file('AndroidManifest.xml'); androidProject.appManifestFile = manifest; - await injectPlugins(flutterProject, androidPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, androidPlatform: true); }, overrides: { FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), @@ -1099,7 +1100,7 @@ flutter: dartPluginClass: SomePlugin '''); - await injectPlugins(flutterProject, androidPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, androidPlatform: true); final File registrantFile = androidProject.pluginRegistrantHost .childDirectory(fs.path.join('src', 'main', 'java', 'io', 'flutter', 'plugins')) @@ -1128,7 +1129,6 @@ flutter: flutterProject, iosPlatform: true, darwinDependencyManagement: dependencyManagement, - useImplicitPubspecResolution: true, ); final File registrantFile = iosProject.pluginRegistrantImplementation; @@ -1156,7 +1156,6 @@ flutter: flutterProject, macOSPlatform: true, darwinDependencyManagement: dependencyManagement, - useImplicitPubspecResolution: true, ); final File registrantFile = macosProject.managedDirectory.childFile('GeneratedPluginRegistrant.swift'); @@ -1185,7 +1184,6 @@ flutter: flutterProject, macOSPlatform: true, darwinDependencyManagement: dependencyManagement, - useImplicitPubspecResolution: true, ); final File registrantFile = macosProject.managedDirectory.childFile('GeneratedPluginRegistrant.swift'); @@ -1210,7 +1208,6 @@ flutter: flutterProject, macOSPlatform: true, darwinDependencyManagement: dependencyManagement, - useImplicitPubspecResolution: true, ); final File registrantFile = macosProject.managedDirectory.childFile('GeneratedPluginRegistrant.swift'); @@ -1224,7 +1221,7 @@ flutter: testUsingContext('Injecting creates generated Linux registrant', () async { createFakePlugin(fs); - await injectPlugins(flutterProject, linuxPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, linuxPlatform: true); final File registrantHeader = linuxProject.managedDirectory.childFile('generated_plugin_registrant.h'); final File registrantImpl = linuxProject.managedDirectory.childFile('generated_plugin_registrant.cc'); @@ -1273,7 +1270,7 @@ dependencies: flutterProject.manifest = manifest; - await injectPlugins(flutterProject, linuxPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, linuxPlatform: true); final File registrantImpl = linuxProject.managedDirectory.childFile('generated_plugin_registrant.cc'); @@ -1331,7 +1328,7 @@ dependencies: flutterProject.manifest = manifest; - await injectPlugins(flutterProject, linuxPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, linuxPlatform: true); final File registrantImpl = linuxProject.managedDirectory.childFile('generated_plugin_registrant.cc'); @@ -1354,7 +1351,7 @@ flutter: dartPluginClass: SomePlugin '''); - await injectPlugins(flutterProject, linuxPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, linuxPlatform: true); final File registrantImpl = linuxProject.managedDirectory.childFile('generated_plugin_registrant.cc'); @@ -1378,7 +1375,7 @@ flutter: dartPluginClass: SomePlugin '''); - await injectPlugins(flutterProject, linuxPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, linuxPlatform: true); final File registrantImpl = linuxProject.managedDirectory.childFile('generated_plugin_registrant.cc'); @@ -1393,7 +1390,7 @@ flutter: testUsingContext('Injecting creates generated Linux plugin Cmake file', () async { createFakePlugin(fs); - await injectPlugins(flutterProject, linuxPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, linuxPlatform: true); final File pluginMakefile = linuxProject.generatedPluginCmakeFile; @@ -1416,7 +1413,7 @@ flutter: '/local_plugins/plugin_b', ]); - await injectPlugins(flutterProject, linuxPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, linuxPlatform: true); final File pluginCmakeFile = linuxProject.generatedPluginCmakeFile; final File pluginRegistrant = linuxProject.managedDirectory.childFile('generated_plugin_registrant.cc'); @@ -1434,7 +1431,7 @@ flutter: testUsingContext('Injecting creates generated Windows registrant', () async { createFakePlugin(fs); - await injectPlugins(flutterProject, windowsPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, windowsPlatform: true); final File registrantHeader = windowsProject.managedDirectory.childFile('generated_plugin_registrant.h'); final File registrantImpl = windowsProject.managedDirectory.childFile('generated_plugin_registrant.cc'); @@ -1458,7 +1455,7 @@ flutter: dartPluginClass: SomePlugin '''); - await injectPlugins(flutterProject, windowsPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, windowsPlatform: true); final File registrantImpl = windowsProject.managedDirectory.childFile('generated_plugin_registrant.cc'); @@ -1481,7 +1478,7 @@ flutter: dartPluginClass: SomePlugin '''); - await injectPlugins(flutterProject, windowsPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, windowsPlatform: true); final File registrantImpl = windowsProject.managedDirectory.childFile('generated_plugin_registrant.cc'); @@ -1501,7 +1498,7 @@ flutter: '/local_plugins/plugin_b', ]); - await injectPlugins(flutterProject, windowsPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, windowsPlatform: true); final File pluginCmakeFile = windowsProject.generatedPluginCmakeFile; final File pluginRegistrant = windowsProject.managedDirectory.childFile('generated_plugin_registrant.cc'); @@ -1521,7 +1518,7 @@ flutter: setUpProject(fsWindows); createFakePlugin(fsWindows); - await injectPlugins(flutterProject, linuxPlatform: true, windowsPlatform: true, useImplicitPubspecResolution: true); + await injectPlugins(flutterProject, linuxPlatform: true, windowsPlatform: true); for (final CmakeBasedProject? project in [linuxProject, windowsProject]) { final File pluginCmakefile = project!.generatedPluginCmakeFile; @@ -1546,7 +1543,6 @@ flutter: linuxPlatform: true, windowsPlatform: true, allowedPlugins: PreviewDevice.supportedPubPlugins, - useImplicitPubspecResolution: true, ), throwsToolExit(message: ''' The Flutter Preview device does not support the following plugins from your pubspec.yaml: @@ -1566,7 +1562,6 @@ The Flutter Preview device does not support the following plugins from your pubs iosPlatform: true, macOSPlatform: true, darwinDependencyManagement: dependencyManagement, - useImplicitPubspecResolution: true, ); expect( dependencyManagement.setupPlatforms, @@ -1582,7 +1577,6 @@ The Flutter Preview device does not support the following plugins from your pubs await injectPlugins( flutterProject, darwinDependencyManagement: dependencyManagement, - useImplicitPubspecResolution: true, ); expect(dependencyManagement.setupPlatforms, []); }, overrides: { @@ -1602,7 +1596,7 @@ The Flutter Preview device does not support the following plugins from your pubs linuxProject.exists = true; createFakePlugin(fs); // refreshPluginsList should call createPluginSymlinks. - await refreshPluginsList(flutterProject, useImplicitPubspecResolution: true); + await refreshPluginsList(flutterProject); expect(linuxProject.pluginSymlinkDirectory.childLink('some_plugin').existsSync(), true); }, overrides: { @@ -1615,7 +1609,7 @@ The Flutter Preview device does not support the following plugins from your pubs windowsProject.exists = true; createFakePlugin(fs); // refreshPluginsList should call createPluginSymlinks. - await refreshPluginsList(flutterProject, useImplicitPubspecResolution: true); + await refreshPluginsList(flutterProject); expect(windowsProject.pluginSymlinkDirectory.childLink('some_plugin').existsSync(), true); }, overrides: { @@ -1661,7 +1655,7 @@ The Flutter Preview device does not support the following plugins from your pubs // refreshPluginsList should remove existing links and recreate on changes. createFakePlugin(fs); - await refreshPluginsList(flutterProject, useImplicitPubspecResolution: true); + await refreshPluginsList(flutterProject); for (final File file in dummyFiles) { expect(file.existsSync(), false); @@ -1700,7 +1694,7 @@ The Flutter Preview device does not support the following plugins from your pubs linuxProject.exists = true; windowsProject.exists = true; createFakePlugin(fs); - await refreshPluginsList(flutterProject, useImplicitPubspecResolution: true); + await refreshPluginsList(flutterProject); final List links = [ linuxProject.pluginSymlinkDirectory.childLink('some_plugin'), diff --git a/packages/flutter_tools/test/general.shard/preview_device_test.dart b/packages/flutter_tools/test/general.shard/preview_device_test.dart index b00fb12fd18..c363186ec88 100644 --- a/packages/flutter_tools/test/general.shard/preview_device_test.dart +++ b/packages/flutter_tools/test/general.shard/preview_device_test.dart @@ -49,7 +49,6 @@ void main() { processManager: FakeProcessManager.any(), previewBinary: previewBinary, logger: BufferLogger.test(), - useImplicitPubspecResolution: true, ); expect(await device.isLocalEmulator, false); @@ -85,7 +84,6 @@ void main() { ]), logger: logger, builderFactory: () => FakeBundleBuilder(fs), - useImplicitPubspecResolution: true, ); final Directory previewDeviceCacheDir = fs .directory('Artifact.windowsDesktopPath.TargetPlatform.windows_x64.debug') @@ -123,7 +121,6 @@ void main() { processManager: processManager, platform: linuxPlatform, featureFlags: featureFlags, - useImplicitPubspecResolution: true, ); final List devices = await discovery.devices(); @@ -139,7 +136,6 @@ void main() { processManager: processManager, platform: macPlatform, featureFlags: featureFlags, - useImplicitPubspecResolution: true, ); final List devices = await discovery.devices(); @@ -157,7 +153,6 @@ void main() { processManager: processManager, platform: windowsPlatform, featureFlags: featureFlags, - useImplicitPubspecResolution: true, ); final List devices = await discovery.devices(); @@ -175,7 +170,6 @@ void main() { processManager: processManager, platform: windowsPlatform, featureFlags: featureFlags, - useImplicitPubspecResolution: true, ); final List devices = await discovery.devices(); @@ -204,7 +198,6 @@ class FakeBundleBuilder extends Fake implements BundleBuilder { String? assetDirPath, bool buildNativeAssets = true, @visibleForTesting BuildSystem? buildSystem, - required bool useImplicitPubspecResolution, }) async { final Directory assetDirectory = fileSystem .directory(assetDirPath) diff --git a/packages/flutter_tools/test/general.shard/project_test.dart b/packages/flutter_tools/test/general.shard/project_test.dart index 6c1e8f15ae6..5180e043e6d 100644 --- a/packages/flutter_tools/test/general.shard/project_test.dart +++ b/packages/flutter_tools/test/general.shard/project_test.dart @@ -141,12 +141,12 @@ void main() { FlutterManifest.empty(logger: logger), FlutterManifest.empty(logger: logger), ); - await project.regeneratePlatformSpecificTooling(useImplicitPubspecResolution: true); + await project.regeneratePlatformSpecificTooling(); expectNotExists(project.directory); }); _testInMemory('does nothing in plugin or package root project', () async { final FlutterProject project = await aPluginProject(); - await project.regeneratePlatformSpecificTooling(useImplicitPubspecResolution: true); + await project.regeneratePlatformSpecificTooling(); expectNotExists(project.ios.hostAppRoot.childDirectory('Runner').childFile('GeneratedPluginRegistrant.h')); expectNotExists(androidPluginRegistrant(project.android.hostAppGradleRoot.childDirectory('app'))); expectNotExists(project.ios.hostAppRoot.childDirectory('Flutter').childFile('Generated.xcconfig')); @@ -158,7 +158,7 @@ void main() { // that a project was a plugin, but shouldn't be as this creates false // positives. project.directory.childDirectory('example').createSync(); - await project.regeneratePlatformSpecificTooling(useImplicitPubspecResolution: true); + await project.regeneratePlatformSpecificTooling(); expectExists(project.ios.hostAppRoot.childDirectory('Runner').childFile('GeneratedPluginRegistrant.h')); expectExists(androidPluginRegistrant(project.android.hostAppGradleRoot.childDirectory('app'))); expectExists(project.ios.hostAppRoot.childDirectory('Flutter').childFile('Generated.xcconfig')); @@ -166,22 +166,22 @@ void main() { }); _testInMemory('injects plugins for iOS', () async { final FlutterProject project = await someProject(); - await project.regeneratePlatformSpecificTooling(useImplicitPubspecResolution: true); + await project.regeneratePlatformSpecificTooling(); expectExists(project.ios.hostAppRoot.childDirectory('Runner').childFile('GeneratedPluginRegistrant.h')); }); _testInMemory('generates Xcode configuration for iOS', () async { final FlutterProject project = await someProject(); - await project.regeneratePlatformSpecificTooling(useImplicitPubspecResolution: true); + await project.regeneratePlatformSpecificTooling(); expectExists(project.ios.hostAppRoot.childDirectory('Flutter').childFile('Generated.xcconfig')); }); _testInMemory('injects plugins for Android', () async { final FlutterProject project = await someProject(); - await project.regeneratePlatformSpecificTooling(useImplicitPubspecResolution: true); + await project.regeneratePlatformSpecificTooling(); expectExists(androidPluginRegistrant(project.android.hostAppGradleRoot.childDirectory('app'))); }); _testInMemory('updates local properties for Android', () async { final FlutterProject project = await someProject(); - await project.regeneratePlatformSpecificTooling(useImplicitPubspecResolution: true); + await project.regeneratePlatformSpecificTooling(); expectExists(project.android.hostAppGradleRoot.childFile('local.properties')); }); _testInMemory('checkForDeprecation fails on invalid android app manifest file', () async { @@ -224,18 +224,18 @@ void main() { final FlutterProject project = await aPluginProject(); project.example.directory.deleteSync(); - await project.regeneratePlatformSpecificTooling(useImplicitPubspecResolution: true); + await project.regeneratePlatformSpecificTooling(); expect(testLogger.statusText, isNot(contains('https://github.com/flutter/flutter/blob/main/docs/platforms/android/Upgrading-pre-1.12-Android-projects.md'))); }); _testInMemory('updates local properties for Android', () async { final FlutterProject project = await someProject(); - await project.regeneratePlatformSpecificTooling(useImplicitPubspecResolution: true); + await project.regeneratePlatformSpecificTooling(); expectExists(project.android.hostAppGradleRoot.childFile('local.properties')); }); testUsingContext('injects plugins for macOS', () async { final FlutterProject project = await someProject(); project.macos.managedDirectory.createSync(recursive: true); - await project.regeneratePlatformSpecificTooling(useImplicitPubspecResolution: true); + await project.regeneratePlatformSpecificTooling(); expectExists(project.macos.pluginRegistrantImplementation); }, overrides: { FileSystem: () => MemoryFileSystem.test(), @@ -249,7 +249,7 @@ void main() { testUsingContext('generates Xcode configuration for macOS', () async { final FlutterProject project = await someProject(); project.macos.managedDirectory.createSync(recursive: true); - await project.regeneratePlatformSpecificTooling(useImplicitPubspecResolution: true); + await project.regeneratePlatformSpecificTooling(); expectExists(project.macos.generatedXcodePropertiesFile); }, overrides: { FileSystem: () => MemoryFileSystem.test(), @@ -263,7 +263,7 @@ void main() { testUsingContext('injects plugins for Linux', () async { final FlutterProject project = await someProject(); project.linux.cmakeFile.createSync(recursive: true); - await project.regeneratePlatformSpecificTooling(useImplicitPubspecResolution: true); + await project.regeneratePlatformSpecificTooling(); expectExists(project.linux.managedDirectory.childFile('generated_plugin_registrant.h')); expectExists(project.linux.managedDirectory.childFile('generated_plugin_registrant.cc')); }, overrides: { @@ -278,7 +278,7 @@ void main() { testUsingContext('injects plugins for Windows', () async { final FlutterProject project = await someProject(); project.windows.cmakeFile.createSync(recursive: true); - await project.regeneratePlatformSpecificTooling(useImplicitPubspecResolution: true); + await project.regeneratePlatformSpecificTooling(); expectExists(project.windows.managedDirectory.childFile('generated_plugin_registrant.h')); expectExists(project.windows.managedDirectory.childFile('generated_plugin_registrant.cc')); }, overrides: { @@ -292,14 +292,14 @@ void main() { }); _testInMemory('creates Android library in module', () async { final FlutterProject project = await aModuleProject(); - await project.regeneratePlatformSpecificTooling(useImplicitPubspecResolution: true); + await project.regeneratePlatformSpecificTooling(); expectExists(project.android.hostAppGradleRoot.childFile('settings.gradle')); expectExists(project.android.hostAppGradleRoot.childFile('local.properties')); expectExists(androidPluginRegistrant(project.android.hostAppGradleRoot.childDirectory('Flutter'))); }); _testInMemory('creates iOS pod in module', () async { final FlutterProject project = await aModuleProject(); - await project.regeneratePlatformSpecificTooling(useImplicitPubspecResolution: true); + await project.regeneratePlatformSpecificTooling(); final Directory flutter = project.ios.hostAppRoot.childDirectory('Flutter'); expectExists(flutter.childFile('podhelper.rb')); expectExists(flutter.childFile('flutter_export_environment.sh')); diff --git a/packages/flutter_tools/test/general.shard/resident_runner_test.dart b/packages/flutter_tools/test/general.shard/resident_runner_test.dart index 6e619fd2ff8..a140cc1f6f5 100644 --- a/packages/flutter_tools/test/general.shard/resident_runner_test.dart +++ b/packages/flutter_tools/test/general.shard/resident_runner_test.dart @@ -63,7 +63,6 @@ void main() { target: 'main.dart', analytics: fakeAnalytics, devtoolsHandler: createNoOpHandler, - useImplicitPubspecResolution: true, ); }, overrides: { Analytics: () => FakeAnalytics(), @@ -115,7 +114,6 @@ void main() { target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: globals.analytics, - useImplicitPubspecResolution: true, ); flutterDevice.generator = residentCompiler; @@ -140,7 +138,6 @@ void main() { target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: globals.analytics, - useImplicitPubspecResolution: true, ); flutterDevice.generator = residentCompiler; @@ -162,7 +159,6 @@ void main() { debuggingOptions: DebuggingOptions.enabled(BuildInfo.release), target: 'main.dart', devtoolsHandler: createNoOpHandler, - useImplicitPubspecResolution: true, ); flutterDevice.runColdCode = 1; @@ -184,7 +180,6 @@ void main() { debuggingOptions: DebuggingOptions.enabled(BuildInfo.release), target: 'main.dart', devtoolsHandler: createNoOpHandler, - useImplicitPubspecResolution: true, ); flutterDevice.runColdError = Exception('BAD STUFF'); @@ -213,7 +208,6 @@ void main() { target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: globals.analytics, - useImplicitPubspecResolution: true, ); flutterDevice.generator = residentCompiler; @@ -274,7 +268,6 @@ void main() { target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: globals.analytics, - useImplicitPubspecResolution: true, ); final Completer futureConnectionInfo = Completer.sync(); final Completer futureAppStart = Completer.sync(); @@ -416,7 +409,6 @@ void main() { enableDevTools: false, ), analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); final Completer futureConnectionInfo = Completer.sync(); final Completer futureAppStart = Completer.sync(); @@ -481,7 +473,6 @@ void main() { target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); final Completer futureConnectionInfo = Completer.sync(); final Completer futureAppStart = Completer.sync(); @@ -746,7 +737,6 @@ void main() { target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); devFS.nextUpdateReport = UpdateFSReport( success: true, @@ -1091,7 +1081,6 @@ void main() { target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); expect(otherRunner.artifactDirectory.path, contains('foobar')); })); @@ -1205,7 +1194,6 @@ flutter: target: 'custom_main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); await residentRunner.runSourceGenerators(); @@ -1266,7 +1254,6 @@ flutter: target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); flutterDevice.generator = residentCompiler; @@ -1367,7 +1354,6 @@ flutter: debuggingOptions: DebuggingOptions.disabled(BuildInfo.release), target: 'main.dart', devtoolsHandler: createNoOpHandler, - useImplicitPubspecResolution: true, ); residentRunner.printHelp(details: true); @@ -1403,7 +1389,6 @@ flutter: debuggingOptions: DebuggingOptions.disabled(BuildInfo.release), target: 'main.dart', devtoolsHandler: createNoOpHandler, - useImplicitPubspecResolution: true, ); residentRunner.printHelp(details: false); @@ -1493,7 +1478,6 @@ flutter: debuggingOptions: DebuggingOptions.enabled(BuildInfo.profile, vmserviceOutFile: 'foo', enableDevTools: false), target: 'main.dart', devtoolsHandler: createNoOpHandler, - useImplicitPubspecResolution: true, ); final Future result = residentRunner.attach(); @@ -1539,7 +1523,6 @@ flutter: target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); await residentRunner.run(); @@ -1570,7 +1553,6 @@ flutter: target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC'); @@ -1602,7 +1584,6 @@ flutter: target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC'); @@ -1635,7 +1616,6 @@ flutter: target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC'); @@ -1660,7 +1640,6 @@ flutter: target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC'); @@ -1686,7 +1665,6 @@ flutter: target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC'); @@ -1716,7 +1694,6 @@ flutter: target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC'); @@ -1740,7 +1717,6 @@ flutter: target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); await residentRunner.run(); @@ -1762,7 +1738,6 @@ flutter: target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); await residentRunner.run(); @@ -1786,7 +1761,6 @@ flutter: debuggingOptions: DebuggingOptions.enabled(BuildInfo.profile, vmserviceOutFile: 'foo'), devtoolsHandler: createNoOpHandler, target: 'main.dart', - useImplicitPubspecResolution: true, ); await residentRunner.run(); @@ -2168,7 +2142,6 @@ flutter: target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); await residentRunner.cleanupAtFinish(); @@ -2190,7 +2163,6 @@ flutter: target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); (flutterDevice.devFS! as FakeDevFS).assetPathsToEvict = {'asset'}; @@ -2216,7 +2188,6 @@ flutter: target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); (flutterDevice.devFS! as FakeDevFS).shaderPathsToEvict = {'foo.frag'}; @@ -2239,7 +2210,6 @@ flutter: target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); expect(flutterDevice.devFS!.hasSetAssetDirectory, false); @@ -2262,7 +2232,6 @@ flutter: target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); (flutterDevice.devFS! as FakeDevFS).assetPathsToEvict = {'asset'}; @@ -2312,7 +2281,6 @@ flutter: devtoolsHandler: createNoOpHandler, analytics: globals.analytics, nativeAssetsYamlFile: 'foo.yaml', - useImplicitPubspecResolution: true, ); final int? result = await residentRunner.run(); diff --git a/packages/flutter_tools/test/general.shard/resident_web_runner_cold_test.dart b/packages/flutter_tools/test/general.shard/resident_web_runner_cold_test.dart index ecef00234cf..ceb06a96a1e 100644 --- a/packages/flutter_tools/test/general.shard/resident_web_runner_cold_test.dart +++ b/packages/flutter_tools/test/general.shard/resident_web_runner_cold_test.dart @@ -61,7 +61,6 @@ void main() { fs: fileSystem, fakeFlutterVersion: FakeFlutterVersion(), ), - useImplicitPubspecResolution: true, ); final Completer connectionInfoCompleter = Completer(); @@ -92,7 +91,6 @@ void main() { fs: fileSystem, fakeFlutterVersion: FakeFlutterVersion(), ), - useImplicitPubspecResolution: true, ); expect(() => residentWebRunner.run(), throwsToolExit()); @@ -118,7 +116,6 @@ void main() { fs: fileSystem, fakeFlutterVersion: FakeFlutterVersion(), ), - useImplicitPubspecResolution: true, ); expect(() async => residentWebRunner.run(), throwsException); @@ -143,7 +140,6 @@ void main() { fs: fileSystem, fakeFlutterVersion: FakeFlutterVersion(), ), - useImplicitPubspecResolution: true, ); final Completer connectionInfoCompleter = Completer(); unawaited(residentWebRunner.run( @@ -173,7 +169,6 @@ void main() { fs: fileSystem, fakeFlutterVersion: FakeFlutterVersion(), ), - useImplicitPubspecResolution: true, ); final Completer connectionInfoCompleter = Completer(); unawaited(residentWebRunner.run( diff --git a/packages/flutter_tools/test/general.shard/resident_web_runner_test.dart b/packages/flutter_tools/test/general.shard/resident_web_runner_test.dart index 108306f7114..6b82c518a82 100644 --- a/packages/flutter_tools/test/general.shard/resident_web_runner_test.dart +++ b/packages/flutter_tools/test/general.shard/resident_web_runner_test.dart @@ -170,7 +170,6 @@ void main() { usage: globals.flutterUsage, analytics: globals.analytics, systemClock: globals.systemClock, - useImplicitPubspecResolution: true, ); expect(profileResidentWebRunner.debuggingEnabled, false); @@ -203,7 +202,6 @@ void main() { usage: globals.flutterUsage, analytics: globals.analytics, systemClock: globals.systemClock, - useImplicitPubspecResolution: true, ); expect(profileResidentWebRunner.uri, webDevFS.baseUri); @@ -223,7 +221,6 @@ void main() { usage: globals.flutterUsage, analytics: globals.analytics, systemClock: globals.systemClock, - useImplicitPubspecResolution: true, ); fakeVmServiceHost = FakeVmServiceHost(requests: []); flutterDevice.device = chromeDevice; @@ -237,7 +234,6 @@ void main() { usage: globals.flutterUsage, analytics: globals.analytics, systemClock: globals.systemClock, - useImplicitPubspecResolution: true, ); expect(profileResidentWebRunner.supportsServiceProtocol, false); @@ -372,7 +368,6 @@ void main() { analytics: globals.analytics, systemClock: globals.systemClock, devtoolsHandler: createNoOpHandler, - useImplicitPubspecResolution: true, ); expect(await residentWebRunner.run(), 0); @@ -400,7 +395,6 @@ void main() { analytics: globals.analytics, systemClock: globals.systemClock, devtoolsHandler: createNoOpHandler, - useImplicitPubspecResolution: true, ); expect(await residentWebRunner.run(), 0); @@ -602,7 +596,6 @@ void main() { analytics: globals.analytics, systemClock: globals.systemClock, devtoolsHandler: createNoOpHandler, - useImplicitPubspecResolution: true, ); fakeVmServiceHost = FakeVmServiceHost(requests: kAttachExpectations.toList()); @@ -1130,7 +1123,6 @@ void main() { analytics: globals.analytics, systemClock: globals.systemClock, devtoolsHandler: createNoOpHandler, - useImplicitPubspecResolution: true, ); final Completer connectionInfoCompleter = @@ -1180,7 +1172,6 @@ void main() { analytics: globals.analytics, systemClock: globals.systemClock, devtoolsHandler: createNoOpHandler, - useImplicitPubspecResolution: true, ); final Completer connectionInfoCompleter = @@ -1224,7 +1215,6 @@ void main() { analytics: globals.analytics, systemClock: globals.systemClock, devtoolsHandler: createNoOpHandler, - useImplicitPubspecResolution: true, ); // Create necessary files. @@ -1481,7 +1471,6 @@ ResidentRunner setUpResidentRunner( fileSystem: globals.fs, logger: logger ?? BufferLogger.test(), devtoolsHandler: createNoOpHandler, - useImplicitPubspecResolution: true, ); } diff --git a/packages/flutter_tools/test/general.shard/tester/flutter_tester_test.dart b/packages/flutter_tools/test/general.shard/tester/flutter_tester_test.dart index fce8dbef67b..672eb9d03c4 100644 --- a/packages/flutter_tools/test/general.shard/tester/flutter_tester_test.dart +++ b/packages/flutter_tools/test/general.shard/tester/flutter_tester_test.dart @@ -98,7 +98,6 @@ void main() { artifacts: Artifacts.test(), logger: BufferLogger.test(), flutterVersion: FakeFlutterVersion(), - useImplicitPubspecResolution: true, ); logLines = []; device.getLogReader().logLines.listen(logLines.add); @@ -218,7 +217,6 @@ FlutterTesterDevices setUpFlutterTesterDevices() { processManager: FakeProcessManager.any(), fileSystem: MemoryFileSystem.test(), flutterVersion: FakeFlutterVersion(), - useImplicitPubspecResolution: true, ); } diff --git a/packages/flutter_tools/test/general.shard/web/compile_web_test.dart b/packages/flutter_tools/test/general.shard/web/compile_web_test.dart index 475a5094947..4cc624f4314 100644 --- a/packages/flutter_tools/test/general.shard/web/compile_web_test.dart +++ b/packages/flutter_tools/test/general.shard/web/compile_web_test.dart @@ -70,7 +70,6 @@ void main() { flutterVersion: flutterVersion, fileSystem: fileSystem, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); await webBuilder.buildWeb( flutterProject, @@ -163,7 +162,6 @@ void main() { flutterVersion: flutterVersion, fileSystem: fileSystem, analytics: fakeAnalytics, - useImplicitPubspecResolution: true, ); await expectLater( () async => webBuilder.buildWeb( diff --git a/packages/flutter_tools/test/src/fakes.dart b/packages/flutter_tools/test/src/fakes.dart index 71ef35c4265..ec5d5296b15 100644 --- a/packages/flutter_tools/test/src/fakes.dart +++ b/packages/flutter_tools/test/src/fakes.dart @@ -482,6 +482,7 @@ class TestFeatureFlags implements FeatureFlags { this.isNativeAssetsEnabled = false, this.isPreviewDeviceEnabled = false, this.isSwiftPackageManagerEnabled = false, + this.isExplicitPackageDependenciesEnabled = false, }); @override @@ -520,6 +521,9 @@ class TestFeatureFlags implements FeatureFlags { @override final bool isSwiftPackageManagerEnabled; + @override + final bool isExplicitPackageDependenciesEnabled; + @override bool isEnabled(Feature feature) { return switch (feature) { @@ -533,6 +537,7 @@ class TestFeatureFlags implements FeatureFlags { flutterCustomDevicesFeature => areCustomDevicesEnabled, cliAnimation => isCliAnimationEnabled, nativeAssets => isNativeAssetsEnabled, + explicitPackageDependencies => isExplicitPackageDependenciesEnabled, _ => false, }; } diff --git a/packages/flutter_tools/test/src/testbed.dart b/packages/flutter_tools/test/src/testbed.dart index b8b86c742cd..27b09d71a27 100644 --- a/packages/flutter_tools/test/src/testbed.dart +++ b/packages/flutter_tools/test/src/testbed.dart @@ -92,7 +92,7 @@ class Testbed { /// /// `overrides` may be used to provide new context values for the single test /// case or override any context values from the setup. - Future run(FutureOr Function() test, {Map? overrides, bool useImplicitPubspecResolution = true}) { + Future run(FutureOr Function() test, {Map? overrides}) { final Map testOverrides = { ..._testbedDefaults, // Add the initial setUp overrides @@ -139,7 +139,7 @@ class Testbed { } return null; }); - }, useImplicitPubspecResolution: useImplicitPubspecResolution); + }); }, createHttpClient: (SecurityContext? c) => FakeHttpClient.any()); } } diff --git a/packages/flutter_tools/test/web.shard/web_driver_service_test.dart b/packages/flutter_tools/test/web.shard/web_driver_service_test.dart index 8d47b72ffd7..6b9cfb8316a 100644 --- a/packages/flutter_tools/test/web.shard/web_driver_service_test.dart +++ b/packages/flutter_tools/test/web.shard/web_driver_service_test.dart @@ -21,7 +21,6 @@ void main() { processManager: FakeProcessManager.empty(), ), dartSdkPath: 'dart', - useImplicitPubspecResolution: true, ); const String link = 'https://flutter.dev/to/integration-test-on-web'; try { From 9a507593c15ebc8b14d95ce6b3db92d08f3eb91a Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Wed, 13 Nov 2024 21:52:08 -0500 Subject: [PATCH 064/386] Roll Flutter Engine from 82940a9aa714 to e97b148e796d (1 revision) (#158901) https://github.com/flutter/engine/compare/82940a9aa714...e97b148e796d 2024-11-13 skia-flutter-autoroll@skia.org Roll Skia from ca10bc19c67e to 3750b8939c7f (2 revisions) (flutter/engine#56560) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index cb38c48c413..40768e77340 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -82940a9aa71453e00e87f25c7d851260cbbd978d +e97b148e796d4d68c6c0a98a78427e4d8ccbafa6 From f38127af0640000580265a07725e4069a8a4b6eb Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Wed, 13 Nov 2024 23:46:41 -0500 Subject: [PATCH 065/386] Roll Flutter Engine from e97b148e796d to 619804c0fbb7 (1 revision) (#158905) https://github.com/flutter/engine/compare/e97b148e796d...619804c0fbb7 2024-11-14 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from z-cm2nR0aJ4lXfwZ0... to JkpuAsLzcmYLzf1iX... (flutter/engine#56570) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from z-cm2nR0aJ4l to JkpuAsLzcmYL If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 40768e77340..861a8240af8 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -e97b148e796d4d68c6c0a98a78427e4d8ccbafa6 +619804c0fbb73452a9296e9144c306e6858a43b4 diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index f378973c9b5..c58a3bfaffb 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -z-cm2nR0aJ4lXfwZ06yE2TbodgbSvTQLHywr_um4fpMC +JkpuAsLzcmYLzf1iXiGQ0p5YoPanCs_DvglyzbIsKNAC From c1ee381b183005c8b6e76e6a447a7f6022951b95 Mon Sep 17 00:00:00 2001 From: Valentin Vignal <32538273+ValentinVignal@users.noreply.github.com> Date: Thu, 14 Nov 2024 16:14:17 +0800 Subject: [PATCH 066/386] Reland Add test for dynamic_content_color.0.dart (#158547) Fixes https://github.com/flutter/flutter/issues/130459 Follow up of the reverted https://github.com/flutter/flutter/pull/158309 It adds a test for - `examples/api/lib/material/color_scheme/dynamic_content_color.0.dart` --- dev/bots/check_code_samples.dart | 42 +--- .../color_scheme/dynamic_content_color.0.dart | 50 +++-- .../dynamic_content_color.0_test.dart | 181 ++++++++++++++++++ 3 files changed, 220 insertions(+), 53 deletions(-) create mode 100644 examples/api/test/material/color_scheme/dynamic_content_color.0_test.dart 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/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/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)); + }); +} From 39dad9946d22e2d87c39c157effe3b71cd801102 Mon Sep 17 00:00:00 2001 From: Bruno Leroux Date: Thu, 14 Nov 2024 10:52:18 +0100 Subject: [PATCH 067/386] Add one MenuAnchor alignment test (#158915) This PR adds a `MenuAnchor` test to check that `MenuAnchor.alignmentOffset` is correctly applied when `MenuAnchor.layerlink` is provided. While reviewing https://github.com/flutter/flutter/pull/158255, I found that this new test would be useful. --- .../test/material/menu_anchor_test.dart | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/packages/flutter/test/material/menu_anchor_test.dart b/packages/flutter/test/material/menu_anchor_test.dart index da35266950c..4216f2ac79c 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', () { From 8f62a9904da06ad20d8e4609cdbb078ed70e8314 Mon Sep 17 00:00:00 2001 From: stuartmorgan Date: Thu, 14 Nov 2024 05:39:39 -0500 Subject: [PATCH 068/386] Update triage flow chart for SVG packages (#158670) Adds special handling of the newly-imported `flutter_svg` and `vector_graphics` family of packages in the triage flow chart, as they should be directed to the engine team. --- docs/triage/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/triage/README.md b/docs/triage/README.md index 9068274328f..25a058b3e4b 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`. From 752ac20f87555bdf9c197e01f1f8bab438ef2394 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Thu, 14 Nov 2024 08:59:49 -0800 Subject: [PATCH 069/386] No longer pass `--verbose` to implicit `pub` calls when `flutter --verbose` is set. (#158898) Closes https://github.com/flutter/flutter/issues/158896. --- packages/flutter_tools/lib/src/dart/pub.dart | 5 +-- .../test/general.shard/dart/pub_get_test.dart | 43 +++++++++++++++++++ 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/packages/flutter_tools/lib/src/dart/pub.dart b/packages/flutter_tools/lib/src/dart/pub.dart index 5e5e539c023..c39de582ba0 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. @@ -353,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), ...[ diff --git a/packages/flutter_tools/test/general.shard/dart/pub_get_test.dart b/packages/flutter_tools/test/general.shard/dart/pub_get_test.dart index 06af2a54625..bdf45033054 100644 --- a/packages/flutter_tools/test/general.shard/dart/pub_get_test.dart +++ b/packages/flutter_tools/test/general.shard/dart/pub_get_test.dart @@ -763,6 +763,49 @@ exit code: 66 expect(processManager, hasNoRemainingExpectations); }); + testWithoutContext('pub get does not inherit logger.verbose', () async { + final BufferLogger logger = BufferLogger.test(verbose: true); + final FileSystem fileSystem = MemoryFileSystem.test(); + fileSystem.currentDirectory.childFile('version').createSync(); + + final FakeProcessManager processManager = FakeProcessManager.list([ + FakeCommand(command: const [ + 'bin/cache/dart-sdk/bin/dart', + // Note: Omitted --verbose. + 'pub', + '--suppress-analytics', + '--directory', + '.', + 'get', + '--example', + ], onRun: (_) { + fileSystem.currentDirectory + .childDirectory('.dart_tool') + .childFile('package_config.json') + .createSync(recursive: true); + }), + ]); + + final Pub pub = Pub.test( + platform: FakePlatform(), + fileSystem: fileSystem, + logger: logger, + usage: TestUsage(), + botDetector: const FakeBotDetector(false), + stdio: FakeStdio(), + processManager: processManager, + ); + + await expectLater( + pub.get( + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + context: PubContext.flutterTests, + outputMode: PubOutputMode.failuresOnly, + ), + completes, + ); + }); + // Regression test for https://github.com/flutter/flutter/issues/116627 testWithoutContext('pub get suppresses progress output', () async { final BufferLogger logger = BufferLogger.test(); From 46a41585ebb0bdf22f881325ceb584b38bdc20a7 Mon Sep 17 00:00:00 2001 From: Camille Simon <43054281+camsim99@users.noreply.github.com> Date: Thu, 14 Nov 2024 10:08:09 -0800 Subject: [PATCH 070/386] Add `dev_dependency` attribute to plugins in `.flutter-plugins-dependencies` (#158009) Adds whether or not the plugins in `.flutter-plugins-dependencies` are dev dependencies or not (as the `dev_dependency` attribute). Fixes https://github.com/flutter/flutter/issues/157948. --- .../lib/src/flutter_plugins.dart | 2 + .../test/general.shard/plugins_test.dart | 15 +- .../flutter_plugins_dependencies_test.dart | 140 ++++++++++++++++++ 3 files changed, 153 insertions(+), 4 deletions(-) create mode 100644 packages/flutter_tools/test/integration.shard/flutter_plugins_dependencies_test.dart diff --git a/packages/flutter_tools/lib/src/flutter_plugins.dart b/packages/flutter_tools/lib/src/flutter_plugins.dart index 5bed044b59e..478baf57cf2 100644 --- a/packages/flutter_tools/lib/src/flutter_plugins.dart +++ b/packages/flutter_tools/lib/src/flutter_plugins.dart @@ -143,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 @@ -270,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; diff --git a/packages/flutter_tools/test/general.shard/plugins_test.dart b/packages/flutter_tools/test/general.shard/plugins_test.dart index 443d94980f9..6d96f15416f 100644 --- a/packages/flutter_tools/test/general.shard/plugins_test.dart +++ b/packages/flutter_tools/test/general.shard/plugins_test.dart @@ -508,6 +508,7 @@ dependencies: 'plugin-b', 'plugin-c', ], + 'dev_dependency': false, }, { 'name': 'plugin-b', @@ -516,12 +517,14 @@ dependencies: 'dependencies': [ 'plugin-c', ], + 'dev_dependency': false, }, { 'name': 'plugin-c', 'path': '${pluginC.path}/', 'native_build': true, 'dependencies': [], + 'dev_dependency': false, }, ]; expect(plugins['ios'], expectedPlugins); @@ -614,7 +617,8 @@ dependencies: 'path': '/.tmp_rand0/flutter_plugin.rand0/', 'shared_darwin_source': true, 'native_build': true, - 'dependencies': [] + 'dependencies': [], + 'dev_dependency': false, } ], 'android': >[ @@ -622,7 +626,8 @@ dependencies: 'name': 'plugin-a', 'path': '/.tmp_rand0/flutter_plugin.rand0/', 'native_build': true, - 'dependencies': [] + 'dependencies': [], + 'dev_dependency': false, } ], 'macos': >[], @@ -632,14 +637,16 @@ dependencies: 'name': 'plugin-a', 'path': '/.tmp_rand0/flutter_plugin.rand0/', 'native_build': false, - 'dependencies': [] + 'dependencies': [], + 'dev_dependency': false, } ], 'web': >[ { 'name': 'plugin-a', 'path': '/.tmp_rand0/flutter_plugin.rand0/', - 'dependencies': [] + 'dependencies': [], + 'dev_dependency': false, } ] }; diff --git a/packages/flutter_tools/test/integration.shard/flutter_plugins_dependencies_test.dart b/packages/flutter_tools/test/integration.shard/flutter_plugins_dependencies_test.dart new file mode 100644 index 00000000000..5939b0aa01b --- /dev/null +++ b/packages/flutter_tools/test/integration.shard/flutter_plugins_dependencies_test.dart @@ -0,0 +1,140 @@ +// 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:file/file.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempProjectDir; + late Directory tempPluginADir; + late Directory tempPluginBDir; + + setUp(() { + tempProjectDir = createResolvedTempDirectorySync( + 'flutter_plugins_dependencies_test_project.'); + tempPluginADir = createResolvedTempDirectorySync( + 'flutter_plugins_dependencies_test_plugin_a.'); + tempPluginBDir = createResolvedTempDirectorySync( + 'flutter_plugins_dependencies_test_plugin_b.'); + }); + + tearDown(() { + tryToDelete(tempProjectDir); + }); + + test( + '.flutter-plugins-dependencies correctly denotes project dev dependencies on all default platforms', + () async { + // Create Flutter project. + final String flutterBin = + fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + + await processManager.run([ + flutterBin, + 'create', + tempProjectDir.path, + '--project-name=testapp', + ], workingDirectory: tempProjectDir.path); + + final File pubspecFile = tempProjectDir.childFile('pubspec.yaml'); + expect(pubspecFile.existsSync(), true); + + // Create Flutter plugins to add as dependencies to Flutter project. + final String pluginAPath = '${tempPluginADir.path}/plugin_a_real_dependency'; + final String pluginBPath = '${tempPluginBDir.path}/plugin_b_dev_dependency'; + + await processManager.run([ + flutterBin, + 'create', + pluginAPath, + '--template=plugin', + '--project-name=plugin_a_real_dependency', + ], workingDirectory: tempPluginADir.path); + + await processManager.run([ + flutterBin, + 'create', + pluginBPath, + '--template=plugin', + '--project-name=plugin_b_dev_dependency', + ], workingDirectory: tempPluginBDir.path); + + // Add dependency on two plugin: one dependency, one dev dependency. + await processManager.run([ + flutterBin, + 'pub', + 'add', + 'plugin_a_real_dependency', + '--path', + pluginAPath, + ], workingDirectory: tempProjectDir.path); + + await processManager.run([ + flutterBin, + 'pub', + 'add', + 'dev:plugin_b_dev_dependency', + '--path', + pluginBPath, + ], workingDirectory: tempProjectDir.path); + + // Run `flutter pub get` to generate .flutter-plugins-dependencies. + await processManager.run([ + flutterBin, + '--no-implicit-pubspec-resolution', + 'pub', + 'get', + ], workingDirectory: tempProjectDir.path); + + final File flutterPluginsDependenciesFile = + tempProjectDir.childFile('.flutter-plugins-dependencies'); + expect(flutterPluginsDependenciesFile.existsSync(), true); + + // Check that .flutter-plugin-dependencies denotes the dependency and + // dev dependency as expected. + final String pluginsString = + flutterPluginsDependenciesFile.readAsStringSync(); + final Map jsonContent = + json.decode(pluginsString) as Map; + final Map plugins = + jsonContent['plugins'] as Map; + + // Loop through all platforms supported by default to verify that the + // dependency and dev dependency are handled appropriately. + final List platformsToVerify = [ + 'ios', + 'android', + 'windows', + 'linux', + 'macos', + 'web', + ]; + + for (final String platform in platformsToVerify) { + final List pluginsForPlatform = + plugins[platform] as List; + + for (final dynamic plugin in pluginsForPlatform) { + final Map pluginProperties = + plugin as Map; + final String pluginName = pluginProperties['name'] as String; + final bool pluginIsDevDependency = + pluginProperties['dev_dependency'] as bool; + + // Check camera dependencies are not marked as dev dependencies. + if (pluginName.startsWith('plugin_a_real_dependency')) { + expect(pluginIsDevDependency, isFalse); + } + + // Check video_player dependencies are marked as dev dependencies. + if (pluginName.startsWith('plugin_b_dev_dependency')) { + expect(pluginIsDevDependency, isTrue); + } + } + } + }); +} From 82380aefe4d6a94231405d692b060c13ef4f9579 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Thu, 14 Nov 2024 13:33:26 -0500 Subject: [PATCH 071/386] Roll Packages from 26e123a6ce03 to b9ac917daeb0 (5 revisions) (#158938) https://github.com/flutter/packages/compare/26e123a6ce03...b9ac917daeb0 2024-11-13 louisehsu@google.com [in_app_purchase_storekit] Fixes manual invocation of `finishTransaction()` triggering fatal crash (flutter/packages#8071) 2024-11-13 49699333+dependabot[bot]@users.noreply.github.com [webview]: Bump androidx.annotation:annotation from 1.8.2 to 1.9.1 in /packages/webview_flutter/webview_flutter_android/android (flutter/packages#7988) 2024-11-13 louisehsu@google.com [in_app_purchase_storekit] Remove unneeded platform annotations (flutter/packages#7914) 2024-11-13 stuartmorgan@google.com [tool] Improve Swift lint error message (flutter/packages#8074) 2024-11-13 engine-flutter-autoroll@skia.org Roll Flutter from c8510f29ccc2 to ed553d10cf63 (48 revisions) (flutter/packages#8076) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-packages-flutter-autoroll Please CC flutter-ecosystem@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/flutter_packages.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/flutter_packages.version b/bin/internal/flutter_packages.version index 1a0a99d903e..9898825b991 100644 --- a/bin/internal/flutter_packages.version +++ b/bin/internal/flutter_packages.version @@ -1 +1 @@ -26e123a6ce039da6b75fe4248e93c8aeeb6d395b +b9ac917daeb0fbf5bd6ad4a7d2a69ab81749d767 From e40306f92f0c818c5615abd5cd2ba89bf4608fc2 Mon Sep 17 00:00:00 2001 From: Ben Konyi Date: Thu, 14 Nov 2024 13:35:16 -0500 Subject: [PATCH 072/386] Enable --verbose for android_plugin_skip_unsupported_test tests (#158933) Hoping this will give some more insights into https://github.com/flutter/flutter/issues/157640 --- .../integration.shard/android_plugin_skip_unsupported_test.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/flutter_tools/test/integration.shard/android_plugin_skip_unsupported_test.dart b/packages/flutter_tools/test/integration.shard/android_plugin_skip_unsupported_test.dart index c52c0b6ee3f..151d0653418 100644 --- a/packages/flutter_tools/test/integration.shard/android_plugin_skip_unsupported_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_plugin_skip_unsupported_test.dart @@ -97,6 +97,8 @@ void main() { 'build', 'apk', '--debug', + // TODO(bkonyi): remove once https://github.com/flutter/flutter/pull/158933 is resolved + '--verbose', ], workingDirectory: pluginExampleAppDir.path); } From 4b818b56c2607ed0f952db48613e0704b77a238f Mon Sep 17 00:00:00 2001 From: Neutrino2711 <98221114+Neutrino2711@users.noreply.github.com> Date: Fri, 15 Nov 2024 01:51:09 +0530 Subject: [PATCH 073/386] Updated document to clarify Clip Behaviour (#157719) Revised comments to clarify that clipping of child depends on clipBehavior of the parent widget, typically scrollable widgets that default to Clips.hard. Noted that decoration features such as shadows , which render outside the widget boundary, may lead to undesirable effects. Recommended using Clips.none in scenarios where shadow effects are used to avoid clipping issues. Fixing Issue #156819 --- .../widgets/sliver/decorated_sliver.1.dart | 158 ++++++++++++++++++ .../sliver/decorated_sliver.1_test.dart | 42 +++++ .../lib/src/widgets/decorated_sliver.dart | 16 +- 3 files changed, 214 insertions(+), 2 deletions(-) create mode 100644 examples/api/lib/widgets/sliver/decorated_sliver.1.dart create mode 100644 examples/api/test/widgets/sliver/decorated_sliver.1_test.dart 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/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/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. From 21144362f86481aadb6fb356c24e5363c72ba375 Mon Sep 17 00:00:00 2001 From: Andrew Kolos Date: Thu, 14 Nov 2024 13:29:30 -0800 Subject: [PATCH 074/386] Move platform-specific log-reading implementation details from `ResidentRunner`/`FlutterDevice` to `DeviceLogReader` implementations (#156181) Cleans up https://github.com/flutter/flutter/pull/155800. In summary, `ResidentRunner`/`FlutterDevice` have branching behavior around logging that depends on the type of `DeviceLogReader` on the `FlutterDevice` instance. Let's instead move this behavior to the `DeviceLogReader` implementations. My apologies for the large diff. Much of this is a refactor that was a bit too difficult to separate into its own commits. Here are the main two changes * Replaces the mutable `connectedVmService` field on the `DeviceLogReader` class with a new method `provideVmService`. This serves largely the same purpose as the mutable field, but it allows for asynchronous code. This is where we put the logic that used to exist in `FlutterDevice.tryInitLogReader`. * Removes the `tryInitLogReader` method from `FlutterDevice`. This method served to set the `appPid` field on the `FlutterDevice`'s `DeviceLogReader` instance. This was only used in the case of Android to filter out logs unrelated to the flutter app coming from the device, so we can move this logic to `AdbLogReader`'s implementation of `provideVmService`. --- .../lib/src/android/android_device.dart | 35 +++++++++++++--- .../lib/src/custom_devices/custom_device.dart | 4 ++ .../flutter_tools/lib/src/desktop_device.dart | 4 ++ packages/flutter_tools/lib/src/device.dart | 14 ++----- .../lib/src/drive/drive_service.dart | 4 +- .../flutter_tools/lib/src/ios/devices.dart | 14 +++---- .../flutter_tools/lib/src/ios/simulators.dart | 4 ++ .../lib/src/proxied_devices/devices.dart | 4 ++ .../lib/src/resident_runner.dart | 22 +--------- packages/flutter_tools/lib/src/run_cold.dart | 4 -- packages/flutter_tools/lib/src/run_hot.dart | 3 +- .../commands.shard/hermetic/daemon_test.dart | 8 +--- .../hermetic/proxied_devices_test.dart | 5 +-- .../android/adb_log_reader_test.dart | 31 +++++++++++++- .../android/android_device_test.dart | 32 +++++++++++++++ .../test/general.shard/cold_test.dart | 3 -- .../drive/drive_service_test.dart | 5 --- .../ios/ios_device_logger_test.dart | 16 ++++---- .../resident_runner_helpers.dart | 3 -- .../general.shard/resident_runner_test.dart | 41 ------------------- .../resident_web_runner_test.dart | 3 -- .../flutter_tools/test/src/fake_devices.dart | 4 ++ 22 files changed, 136 insertions(+), 127 deletions(-) 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/custom_devices/custom_device.dart b/packages/flutter_tools/lib/src/custom_devices/custom_device.dart index 4de1502151e..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. 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/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 bf6ccb6f017..bb7473d0851 100644 --- a/packages/flutter_tools/lib/src/drive/drive_service.dart +++ b/packages/flutter_tools/lib/src/drive/drive_service.dart @@ -231,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/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/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/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_runner.dart b/packages/flutter_tools/lib/src/resident_runner.dart index af8aabbea5d..2e2ee0dc98a 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, diff --git a/packages/flutter_tools/lib/src/run_cold.dart b/packages/flutter_tools/lib/src/run_cold.dart index 55e699cdc14..cfe5979d1e1 100644 --- a/packages/flutter_tools/lib/src/run_cold.dart +++ b/packages/flutter_tools/lib/src/run_cold.dart @@ -104,7 +104,6 @@ class ColdRunner extends ResidentRunner { if (device!.vmService == null) { continue; } - await device.tryInitLogReader(); globals.printTrace('Connected to ${device.device!.name}'); } @@ -153,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 dc27fd0bf37..9eb5fc121d0 100644 --- a/packages/flutter_tools/lib/src/run_hot.dart +++ b/packages/flutter_tools/lib/src/run_hot.dart @@ -261,8 +261,7 @@ class HotRunner extends ResidentRunner { } for (final FlutterDevice? device in flutterDevices) { - await device!.tryInitLogReader(); - device + device! .developmentShaderCompiler .configureCompiler(device.targetPlatform); } 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 4e62f13b903..4f998d84739 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/daemon_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/daemon_test.dart @@ -1262,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; @@ -1279,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/proxied_devices_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/proxied_devices_test.dart index 35468443cbb..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 @@ -354,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/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/cold_test.dart b/packages/flutter_tools/test/general.shard/cold_test.dart index 51521645e4f..6fa138d1b8e 100644 --- a/packages/flutter_tools/test/general.shard/cold_test.dart +++ b/packages/flutter_tools/test/general.shard/cold_test.dart @@ -163,9 +163,6 @@ class FakeFlutterDevice extends Fake implements FlutterDevice { Future runCold({ColdRunner? coldRunner, String? route}) async { return runColdCode; } - - @override - Future tryInitLogReader() async { } } class FakeDevice extends Fake implements Device { diff --git a/packages/flutter_tools/test/general.shard/drive/drive_service_test.dart b/packages/flutter_tools/test/general.shard/drive/drive_service_test.dart index 4bc504b2d08..1065ef83e8e 100644 --- a/packages/flutter_tools/test/general.shard/drive/drive_service_test.dart +++ b/packages/flutter_tools/test/general.shard/drive/drive_service_test.dart @@ -273,7 +273,6 @@ void main() { testUsingContext('Writes SkSL to file when provided with out file', () async { final MemoryFileSystem fileSystem = MemoryFileSystem.test(); final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ - getVM, listViews, const FakeVmServiceRequest( method: '_flutter.getSkSLs', @@ -310,7 +309,6 @@ void main() { testWithoutContext('Can connect to existing application and stop it during cleanup', () async { final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ - getVM, getVM, const FakeVmServiceRequest( method: 'ext.flutter.exit', @@ -333,7 +331,6 @@ void main() { testWithoutContext('Can connect to existing application using ws URI', () async { final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ - getVM, getVM, const FakeVmServiceRequest( method: 'ext.flutter.exit', @@ -356,7 +353,6 @@ void main() { testWithoutContext('Can connect to existing application using ws URI (no trailing slash)', () async { final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ - getVM, getVM, const FakeVmServiceRequest( method: 'ext.flutter.exit', @@ -379,7 +375,6 @@ void main() { testWithoutContext('Can connect to existing application using ws URI (no trailing slash, ws in auth code)', () async { final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ - getVM, getVM, const FakeVmServiceRequest( method: 'ext.flutter.exit', diff --git a/packages/flutter_tools/test/general.shard/ios/ios_device_logger_test.dart b/packages/flutter_tools/test/general.shard/ios/ios_device_logger_test.dart index c113334ba03..6d3839f8b1f 100644 --- a/packages/flutter_tools/test/general.shard/ios/ios_device_logger_test.dart +++ b/packages/flutter_tools/test/general.shard/ios/ios_device_logger_test.dart @@ -181,7 +181,7 @@ Runner(libsystem_asl.dylib)[297] : libMobileGestalt logger: logger, ), ); - logReader.connectedVMService = vmService; + await logReader.provideVmService(vmService); // Wait for stream listeners to fire. await expectLater(logReader.logLines, emitsInAnyOrder([ @@ -223,7 +223,7 @@ Runner(libsystem_asl.dylib)[297] : libMobileGestalt logger: logger, ), ); - logReader.connectedVMService = vmService; + await logReader.provideVmService(vmService); final FakeIOSDeployDebugger iosDeployDebugger = FakeIOSDeployDebugger(); iosDeployDebugger.debuggerAttached = true; @@ -425,7 +425,7 @@ Runner(libsystem_asl.dylib)[297] : libMobileGestalt expect(logReader.logSources.fallbackSource, IOSDeviceLogSource.unifiedLogging); }); - testWithoutContext('for iOS 13 or greater non-CoreDevice, _iosDeployDebugger not attached, and VM is connected', () { + testWithoutContext('for iOS 13 or greater non-CoreDevice, _iosDeployDebugger not attached, and VM is connected', () async { final IOSDeviceLogReader logReader = IOSDeviceLogReader.test( iMobileDevice: IMobileDevice( artifacts: artifacts, @@ -448,7 +448,7 @@ Runner(libsystem_asl.dylib)[297] : libMobileGestalt }), ]).vmService; - logReader.connectedVMService = vmService; + await logReader.provideVmService(vmService); expect(logReader.useSyslogLogging, isFalse); expect(logReader.useUnifiedLogging, isTrue); @@ -457,7 +457,7 @@ Runner(libsystem_asl.dylib)[297] : libMobileGestalt expect(logReader.logSources.fallbackSource, IOSDeviceLogSource.iosDeploy); }); - testWithoutContext('for iOS 13 or greater non-CoreDevice and _iosDeployDebugger is attached', () { + testWithoutContext('for iOS 13 or greater non-CoreDevice and _iosDeployDebugger is attached', () async { final IOSDeviceLogReader logReader = IOSDeviceLogReader.test( iMobileDevice: IMobileDevice( artifacts: artifacts, @@ -484,7 +484,7 @@ Runner(libsystem_asl.dylib)[297] : libMobileGestalt }), ]).vmService; - logReader.connectedVMService = vmService; + await logReader.provideVmService(vmService); expect(logReader.useSyslogLogging, isFalse); expect(logReader.useUnifiedLogging, isTrue); @@ -685,7 +685,7 @@ Runner(libsystem_asl.dylib)[297] : libMobileGestalt logger: logger, ), ); - logReader.connectedVMService = vmService; + await logReader.provideVmService(vmService); // Wait for stream listeners to fire. expect(logReader.useUnifiedLogging, isTrue); @@ -729,7 +729,7 @@ Runner(libsystem_asl.dylib)[297] : libMobileGestalt ), majorSdkVersion: 12, ); - logReader.connectedVMService = vmService; + await logReader.provideVmService(vmService); final List lines = await logReader.logLines.toList(); diff --git a/packages/flutter_tools/test/general.shard/resident_runner_helpers.dart b/packages/flutter_tools/test/general.shard/resident_runner_helpers.dart index e350513d2a2..1aa10fc0e99 100644 --- a/packages/flutter_tools/test/general.shard/resident_runner_helpers.dart +++ b/packages/flutter_tools/test/general.shard/resident_runner_helpers.dart @@ -227,9 +227,6 @@ class FakeFlutterDevice extends Fake implements FlutterDevice { @override Future stopEchoingDeviceLog() async { } - @override - Future tryInitLogReader() async { } - @override Future setupDevFS(String fsName, Directory rootDirectory) async { return testUri!; diff --git a/packages/flutter_tools/test/general.shard/resident_runner_test.dart b/packages/flutter_tools/test/general.shard/resident_runner_test.dart index a140cc1f6f5..545c6d42943 100644 --- a/packages/flutter_tools/test/general.shard/resident_runner_test.dart +++ b/packages/flutter_tools/test/general.shard/resident_runner_test.dart @@ -682,10 +682,6 @@ void main() { testUsingContext('ResidentRunner reports hot reload time details', () => testbed.run(() async { fakeVmServiceHost = FakeVmServiceHost(requests: [ listViews, - FakeVmServiceRequest( - method: 'getVM', - jsonResponse: fakeVM.toJson(), - ), listViews, listViews, FakeVmServiceRequest( @@ -1929,43 +1925,6 @@ flutter: ProcessManager: () => FakeProcessManager.any(), }); - testUsingContext('FlutterDevice does not throw when unable to initiate log reader due to VM service disconnection', () async { - fakeVmServiceHost = FakeVmServiceHost( - requests: [ - FakeVmServiceRequest( - method: 'getVM', - error: FakeRPCError( - code: vm_service.RPCErrorKind.kServerError.code, - error: 'Service connection disposed', - ), - ), - ], - ); - final TestFlutterDevice flutterDevice = TestFlutterDevice(device); - flutterDevice.vmService = fakeVmServiceHost!.vmService; - await flutterDevice.tryInitLogReader(); - - final BufferLogger logger = globals.logger as BufferLogger; - expect( - logger.traceText, - contains( - 'VmService.getVm call failed: getVM: (-32000) ' - 'Service connection disposed\n', - ), - ); - // We should not print a warning since the device does not have a connected - // adb log reader. - // TODO(andrewkolos): This test is a bit fragile, and is something that - // should be corrected in a follow-up PR (see - // https://github.com/flutter/flutter/issues/155795). - expect(logger.errorText, isEmpty); - }, overrides: { - Logger: () => BufferLogger.test(), - Artifacts: () => Artifacts.test(), - FileSystem: () => MemoryFileSystem.test(), - ProcessManager: () => FakeProcessManager.any(), - }); - testUsingContext('Uses existing DDS URI from exception field', () => testbed.run(() async { fakeVmServiceHost = FakeVmServiceHost(requests: []); final FakeDevice device = FakeDevice() diff --git a/packages/flutter_tools/test/general.shard/resident_web_runner_test.dart b/packages/flutter_tools/test/general.shard/resident_web_runner_test.dart index 6b82c518a82..b9695f7690a 100644 --- a/packages/flutter_tools/test/general.shard/resident_web_runner_test.dart +++ b/packages/flutter_tools/test/general.shard/resident_web_runner_test.dart @@ -1760,9 +1760,6 @@ class FakeFlutterDevice extends Fake implements FlutterDevice { @override Future stopEchoingDeviceLog() async {} - @override - Future tryInitLogReader() async {} - @override Future setupDevFS(String fsName, Directory rootDirectory) async { return testUri; diff --git a/packages/flutter_tools/test/src/fake_devices.dart b/packages/flutter_tools/test/src/fake_devices.dart index 55862443270..1a661781658 100644 --- a/packages/flutter_tools/test/src/fake_devices.dart +++ b/packages/flutter_tools/test/src/fake_devices.dart @@ -8,6 +8,7 @@ import 'package:flutter_tools/src/application_package.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/device.dart'; import 'package:flutter_tools/src/project.dart'; +import 'package:flutter_tools/src/vmservice.dart'; import 'fakes.dart'; @@ -311,4 +312,7 @@ class FakeDeviceLogReader extends DeviceLogReader { await _linesController.close(); disposed = true; } + + @override + Future provideVmService(FlutterVmService? connectedVmService) async { } } From a1a7409092ff1be0f6e7fa6f3418c431881ae957 Mon Sep 17 00:00:00 2001 From: Andrew Kolos Date: Thu, 14 Nov 2024 13:46:10 -0800 Subject: [PATCH 075/386] hide members where possible (#158492) I was poking around in logger.dart when I noticed a few classes have unnecessary exposed member variables. This PR reduces visibility of these in the pursuit of making these classes slightly easier to grok.
Pre-launch checklist
--- .../flutter_tools/lib/src/base/logger.dart | 116 ++++++++++-------- 1 file changed, 62 insertions(+), 54 deletions(-) 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'); } From f35cd558f8a8f3594492eac6b9a12be0cf370d63 Mon Sep 17 00:00:00 2001 From: August Date: Thu, 14 Nov 2024 22:48:12 +0100 Subject: [PATCH 076/386] feat: Include web 1.x.x in plugin template (#156947) This adds support for web 1.x.x to be included in the plugin template, when creating a web plugin. I don't have an issue referenced. Related to https://github.com/dart-lang/web/issues/316 --- .../flutter_tools/templates/plugin_shared/pubspec.yaml.tmpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From dca37ad17ff0354924f9b5bbbcbb2ce6ed819230 Mon Sep 17 00:00:00 2001 From: kzrnm Date: Fri, 15 Nov 2024 06:48:14 +0900 Subject: [PATCH 077/386] [gen_l10n] When localizing a message, prefer placeholder definitions defined by the current locale rather than the template locale (#153459) - Fixes #153457 - Fixes #116716 --- .../lib/src/localizations/gen_l10n.dart | 61 ++- .../src/localizations/gen_l10n_templates.dart | 4 +- .../lib/src/localizations/gen_l10n_types.dart | 35 +- .../generate_localizations_test.dart | 396 +++++++++++++++++- 4 files changed, 453 insertions(+), 43 deletions(-) diff --git a/packages/flutter_tools/lib/src/localizations/gen_l10n.dart b/packages/flutter_tools/lib/src/localizations/gen_l10n.dart index 781602346f9..0ef68cff42a 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; @@ -177,12 +190,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 +255,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 +623,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 +1002,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 +1151,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 +1161,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 +1198,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 +1260,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 +1284,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 +1319,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..3f15740c46b 100644 --- a/packages/flutter_tools/lib/src/localizations/gen_l10n_templates.dart +++ b/packages/flutter_tools/lib/src/localizations/gen_l10n_templates.dart @@ -171,7 +171,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..2bae97f0f83 100644 --- a/packages/flutter_tools/lib/src/localizations/gen_l10n_types.dart +++ b/packages/flutter_tools/lib/src/localizations/gen_l10n_types.dart @@ -347,7 +347,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 +358,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 +384,7 @@ class Message { } } // Infer the placeholders - _inferPlaceholders(filenames); + _inferPlaceholders(); } final String resourceId; @@ -386,13 +392,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 +502,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 +546,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 +559,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) { diff --git a/packages/flutter_tools/test/general.shard/generate_localizations_test.dart b/packages/flutter_tools/test/general.shard/generate_localizations_test.dart index 068bb6830f9..55a33a294be 100644 --- a/packages/flutter_tools/test/general.shard/generate_localizations_test.dart +++ b/packages/flutter_tools/test/general.shard/generate_localizations_test.dart @@ -792,6 +792,8 @@ flutter: expect(fs.file('/lib/l10n/bar_en.dart').readAsStringSync(), ''' HEADER +// ignore: unused_import +import 'package:intl/intl.dart' as intl; import 'bar.dart'; // ignore_for_file: type=lint @@ -894,6 +896,8 @@ flutter:\r ); expect(fs.file('/lib/l10n/app_localizations_en.dart').readAsStringSync(), ''' +// ignore: unused_import +import 'package:intl/intl.dart' as intl; import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -927,6 +931,8 @@ class AppLocalizationsEn extends AppLocalizations { expect(fs.file('/lib/l10n/app_localizations_en.dart').readAsStringSync(), ''' HEADER +// ignore: unused_import +import 'package:intl/intl.dart' as intl; import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1705,6 +1711,270 @@ import 'output-localization-file_en.dart' deferred as output-localization-file_e )), ); }); + + testWithoutContext('handle date with multiple locale', () { + setupLocalizations({ + 'en': ''' +{ + "@@locale": "en", + "springBegins": "Spring begins on {springStartDate}", + "@springBegins": { + "description": "The first day of spring", + "placeholders": { + "springStartDate": { + "type": "DateTime", + "format": "MMMd" + } + } + } +}''', + 'ja': ''' +{ + "@@locale": "ja", + "springBegins": "春が始まるのは{springStartDate}", + "@springBegins": { + "placeholders": { + "springStartDate": { + "type": "DateTime", + "format": "MMMMd" + } + } + } +}''' + }); + + expect(getGeneratedFileContent(locale: 'en'), contains('intl.DateFormat.MMMd(localeName)')); + expect(getGeneratedFileContent(locale: 'ja'), contains('intl.DateFormat.MMMMd(localeName)')); + expect(getGeneratedFileContent(locale: 'en'), contains('String springBegins(DateTime springStartDate)')); + expect(getGeneratedFileContent(locale: 'ja'), contains('String springBegins(DateTime springStartDate)')); + }); + + testWithoutContext('handle date with multiple locale when only template has placeholders', () { + setupLocalizations({ + 'en': ''' +{ + "@@locale": "en", + "springBegins": "Spring begins on {springStartDate}", + "@springBegins": { + "description": "The first day of spring", + "placeholders": { + "springStartDate": { + "type": "DateTime", + "format": "MMMd" + } + } + } +}''', + 'ja': ''' +{ + "@@locale": "ja", + "springBegins": "春が始まるのは{springStartDate}" +}''' + }); + + expect(getGeneratedFileContent(locale: 'en'), contains('intl.DateFormat.MMMd(localeName)')); + expect(getGeneratedFileContent(locale: 'ja'), contains('intl.DateFormat.MMMd(localeName)')); + expect(getGeneratedFileContent(locale: 'en'), contains('String springBegins(DateTime springStartDate)')); + expect(getGeneratedFileContent(locale: 'ja'), contains('String springBegins(DateTime springStartDate)')); + }); + + testWithoutContext('handle date with multiple locale when there is unused placeholder', () { + setupLocalizations({ + 'en': ''' +{ + "@@locale": "en", + "springBegins": "Spring begins on {springStartDate}", + "@springBegins": { + "description": "The first day of spring", + "placeholders": { + "springStartDate": { + "type": "DateTime", + "format": "MMMd" + } + } + } +}''', + 'ja': ''' +{ + "@@locale": "ja", + "springBegins": "春が始まるのは{springStartDate}", + "@springBegins": { + "description": "The first day of spring", + "placeholders": { + "notUsed": { + "type": "DateTime", + "format": "MMMMd" + } + } + } +}''' + }); + + expect(getGeneratedFileContent(locale: 'en'), contains('intl.DateFormat.MMMd(localeName)')); + expect(getGeneratedFileContent(locale: 'ja'), contains('intl.DateFormat.MMMd(localeName)')); + expect(getGeneratedFileContent(locale: 'en'), contains('String springBegins(DateTime springStartDate)')); + expect(getGeneratedFileContent(locale: 'ja'), contains('String springBegins(DateTime springStartDate)')); + expect(getGeneratedFileContent(locale: 'ja'), isNot(contains('notUsed'))); + }); + + testWithoutContext('handle date with multiple locale when placeholders are incompatible', () { + expect( + () { + setupLocalizations({ + 'en': ''' + { + "@@locale": "en", + "springBegins": "Spring begins on {springStartDate}", + "@springBegins": { + "description": "The first day of spring", + "placeholders": { + "springStartDate": { + "type": "DateTime", + "format": "MMMd" + } + } + } + }''', + 'ja': ''' + { + "@@locale": "ja", + "springBegins": "春が始まるのは{springStartDate}", + "@springBegins": { + "description": "The first day of spring", + "placeholders": { + "springStartDate": { + "type": "String" + } + } + } + }''' + }); + }, + throwsA(isA().having( + (L10nException e) => e.message, + 'message', + contains('The placeholder, springStartDate, has its "type" resource attribute set to the "String" type in locale "ja", but it is "DateTime" in the template placeholder.'), + )), + ); + }); + + testWithoutContext('handle date with multiple locale when non-template placeholder does not specify type', () { + expect( + () { + setupLocalizations({ + 'en': ''' + { + "@@locale": "en", + "springBegins": "Spring begins on {springStartDate}", + "@springBegins": { + "description": "The first day of spring", + "placeholders": { + "springStartDate": { + "type": "DateTime", + "format": "MMMd" + } + } + } + }''', + 'ja': ''' + { + "@@locale": "ja", + "springBegins": "春が始まるのは{springStartDate}", + "@springBegins": { + "description": "The first day of spring", + "placeholders": { + "springStartDate": { + "format": "MMMMd" + } + } + } + }''' + }); + }, + throwsA(isA().having( + (L10nException e) => e.message, + 'message', + contains('The placeholder, springStartDate, has its "type" resource attribute set to the "null" type in locale "ja", but it is "DateTime" in the template placeholder.'), + )), + ); + }); + + testWithoutContext('handle ordinary formatted date and arbitrary formatted date', () { + setupLocalizations({ + 'en': ''' +{ + "@@locale": "en", + "springBegins": "Spring begins on {springStartDate}", + "@springBegins": { + "description": "The first day of spring", + "placeholders": { + "springStartDate": { + "type": "DateTime", + "format": "MMMd" + } + } + } +}''', + 'ja': ''' +{ + "@@locale": "ja", + "springBegins": "春が始まるのは{springStartDate}", + "@springBegins": { + "placeholders": { + "springStartDate": { + "type": "DateTime", + "format": "立春", + "isCustomDateFormat": "true" + } + } + } +}''' + }); + + expect(getGeneratedFileContent(locale: 'en'), contains('intl.DateFormat.MMMd(localeName)')); + expect(getGeneratedFileContent(locale: 'ja'), contains(r"DateFormat('立春', localeName)")); + expect(getGeneratedFileContent(locale: 'en'), contains('String springBegins(DateTime springStartDate)')); + expect(getGeneratedFileContent(locale: 'ja'), contains('String springBegins(DateTime springStartDate)')); + }); + + testWithoutContext('handle arbitrary formatted date with multiple locale', () { + setupLocalizations({ + 'en': ''' +{ + "@@locale": "en", + "springBegins": "Spring begins on {springStartDate}", + "@springBegins": { + "description": "The first day of spring", + "placeholders": { + "springStartDate": { + "type": "DateTime", + "format": "asdf o'clock", + "isCustomDateFormat": "true" + } + } + } +}''', + 'ja': ''' +{ + "@@locale": "ja", + "springBegins": "春が始まるのは{springStartDate}", + "@springBegins": { + "placeholders": { + "springStartDate": { + "type": "DateTime", + "format": "立春", + "isCustomDateFormat": "true" + } + } + } +}''' + }); + + expect(getGeneratedFileContent(locale: 'en'), contains(r"DateFormat('asdf o\'clock', localeName)")); + expect(getGeneratedFileContent(locale: 'ja'), contains(r"DateFormat('立春', localeName)")); + expect(getGeneratedFileContent(locale: 'en'), contains('String springBegins(DateTime springStartDate)')); + expect(getGeneratedFileContent(locale: 'ja'), contains('String springBegins(DateTime springStartDate)')); + }); }); group('NumberFormat tests', () { @@ -1766,7 +2036,7 @@ import 'output-localization-file_en.dart' deferred as output-localization-file_e 'en': singleMessageArbFileString, 'es': singleEsMessageArbFileString, }); - expect(getGeneratedFileContent(locale: 'es'), isNot(contains(intlImportDartCode))); + expect(getGeneratedFileContent(locale: 'es'), contains(intlImportDartCode)); }); testWithoutContext('warnings are generated when plural parts are repeated', () { @@ -2425,6 +2695,128 @@ import 'output-localization-file_en.dart' deferred as output-localization-file_e )), ); }); + + testWithoutContext('handle number with multiple locale', () { + setupLocalizations({ + 'en': ''' +{ +"@@locale": "en", +"money": "Sum {number}", +"@money": { + "placeholders": { + "number": { + "type": "int", + "format": "currency" + } + } +} +}''', + 'ja': ''' +{ +"@@locale": "ja", +"money": "合計 {number}", +"@money": { + "placeholders": { + "number": { + "type": "int", + "format": "decimalPatternDigits", + "optionalParameters": { + "decimalDigits": 3 + } + } + } +} +}''' + }); + + expect(getGeneratedFileContent(locale: 'en'), contains('String money(int number)')); + expect(getGeneratedFileContent(locale: 'ja'), contains('String money(int number)')); + expect(getGeneratedFileContent(locale: 'en'), contains('intl.NumberFormat.currency(')); + expect(getGeneratedFileContent(locale: 'ja'), contains('intl.NumberFormat.decimalPatternDigits(')); + expect(getGeneratedFileContent(locale: 'ja'), contains('decimalDigits: 3')); + }); + + testWithoutContext('handle number with multiple locale specifying a format only in template', () { + setupLocalizations({ + 'en': ''' +{ +"@@locale": "en", +"money": "Sum {number}", +"@money": { + "placeholders": { + "number": { + "type": "int", + "format": "decimalPatternDigits", + "optionalParameters": { + "decimalDigits": 3 + } + } + } +} +}''', + 'ja': ''' +{ +"@@locale": "ja", +"money": "合計 {number}", +"@money": { + "placeholders": { + "number": { + "type": "int" + } + } +} +}''' + }); + + expect(getGeneratedFileContent(locale: 'en'), contains('String money(int number)')); + expect(getGeneratedFileContent(locale: 'ja'), contains('String money(int number)')); + expect(getGeneratedFileContent(locale: 'en'), contains('intl.NumberFormat.decimalPatternDigits(')); + expect(getGeneratedFileContent(locale: 'en'), contains('decimalDigits: 3')); + expect(getGeneratedFileContent(locale: 'en'), contains(r"return 'Sum $numberString'")); + expect(getGeneratedFileContent(locale: 'ja'), isNot(contains('intl.NumberFormat'))); + expect(getGeneratedFileContent(locale: 'ja'), contains(r"return '合計 $number'")); + }); + + testWithoutContext('handle number with multiple locale specifying a format only in non-template', () { + setupLocalizations({ + 'en': ''' +{ +"@@locale": "en", +"money": "Sum {number}", +"@money": { + "placeholders": { + "number": { + "type": "int" + } + } +} +}''', + 'ja': ''' +{ +"@@locale": "ja", +"money": "合計 {number}", +"@money": { + "placeholders": { + "number": { + "type": "int", + "format": "decimalPatternDigits", + "optionalParameters": { + "decimalDigits": 3 + } + } + } +} +}''' + }); + + expect(getGeneratedFileContent(locale: 'en'), contains('String money(int number)')); + expect(getGeneratedFileContent(locale: 'ja'), contains('String money(int number)')); + expect(getGeneratedFileContent(locale: 'en'), isNot(contains('intl.NumberFormat'))); + expect(getGeneratedFileContent(locale: 'en'), contains(r"return 'Sum $number'")); + expect(getGeneratedFileContent(locale: 'ja'), contains('intl.NumberFormat.decimalPatternDigits(')); + expect(getGeneratedFileContent(locale: 'ja'), contains('decimalDigits: 3')); + expect(getGeneratedFileContent(locale: 'ja'), contains(r"return '合計 $numberString'")); + }); }); testWithoutContext('should generate a valid pubspec.yaml file when using synthetic package if it does not already exist', () { @@ -2477,7 +2869,7 @@ String orderNumber(int number) { return 'This is order #$number.'; } ''')); - expect(getGeneratedFileContent(locale: 'en'), isNot(contains(intlImportDartCode))); + expect(getGeneratedFileContent(locale: 'en'), contains(intlImportDartCode)); }); testWithoutContext('app localizations lookup is a public method', () { From f4c02036ece4cd36e77a929de538cabe06a20edb Mon Sep 17 00:00:00 2001 From: Flutter GitHub Bot Date: Thu, 14 Nov 2024 17:16:24 -0500 Subject: [PATCH 078/386] Marks Mac_arm64 mac_desktop_impeller to be unflaky (#158564) The test has been passing for [50 consecutive runs](https://data.corp.google.com/sites/flutter_infra_metrics_datasite/flutter_check_test_flakiness_status_dashboard/?p=BUILDER_NAME:%22Mac_arm64%20mac_desktop_impeller%22). This test can be marked as unflaky. --- .ci.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/.ci.yaml b/.ci.yaml index 873c01617f2..9ac5b72b11f 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -5428,7 +5428,6 @@ targets: - name: Mac_arm64 mac_desktop_impeller recipe: devicelab/devicelab_drone presubmit: false - bringup: true timeout: 60 properties: dependencies: >- From b77db0b44af9a1d56b38a830422899ddfa74c1b0 Mon Sep 17 00:00:00 2001 From: Flutter GitHub Bot Date: Thu, 14 Nov 2024 17:26:30 -0500 Subject: [PATCH 079/386] Marks Mac_x64 hot_mode_dev_cycle_macos_target__benchmark to be flaky (#158569) Issue link: https://github.com/flutter/flutter/issues/158568 --- .ci.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.ci.yaml b/.ci.yaml index 9ac5b72b11f..83183f33557 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -4896,6 +4896,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: From 34b5c274bbbb717621b0441dc5b6f79ca5e61993 Mon Sep 17 00:00:00 2001 From: Kate Lovett Date: Thu, 14 Nov 2024 15:50:05 -0800 Subject: [PATCH 080/386] Create merge_queue.md (#158959) Adds information on the merge queue, to be used for announcement. Will update to final doc after the merge project is complete. --- docs/infra/merge_queue.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 docs/infra/merge_queue.md diff --git a/docs/infra/merge_queue.md b/docs/infra/merge_queue.md new file mode 100644 index 00000000000..dd8bdebf07e --- /dev/null +++ b/docs/infra/merge_queue.md @@ -0,0 +1,34 @@ +## Github Merge Queue + +If you are not hacking on flutter/flutter, you can stop reading now. + +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 15, 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. +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, @jtmcdole, @christopherfujino, @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. From d0bd283734ca7d55b867d0dc2063dd68e3f883f2 Mon Sep 17 00:00:00 2001 From: Ben Konyi Date: Thu, 14 Nov 2024 19:43:15 -0500 Subject: [PATCH 081/386] [ tool ] Don't throw StateError when DDS fails to start (#158744) This started happening after moving DDS to launch from `dart development-service` rather than `DartDevelopmentService` (see 33b402d24c2131dcf97e272ec3d59c0249762e7f) . This state error was originally meant to be thrown when some string parsing failed, but is currently wrapping the `DartDevelopmentServiceException`. Fixes https://github.com/flutter/flutter/issues/158537 --- packages/flutter_tools/lib/src/base/dds.dart | 11 ---- .../general.shard/resident_runner_test.dart | 59 ------------------- 2 files changed, 70 deletions(-) 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/test/general.shard/resident_runner_test.dart b/packages/flutter_tools/test/general.shard/resident_runner_test.dart index 545c6d42943..275a5b6f24f 100644 --- a/packages/flutter_tools/test/general.shard/resident_runner_test.dart +++ b/packages/flutter_tools/test/general.shard/resident_runner_test.dart @@ -2021,65 +2021,6 @@ flutter: }) async => FakeVmServiceHost(requests: []).vmService, })); - testUsingContext('Failed DDS start outputs error message', () => testbed.run(() async { - // See https://github.com/flutter/flutter/issues/72385 for context. - final FakeDevice device = FakeDevice() - ..dds = DartDevelopmentService(logger: testLogger); - ddsLauncherCallback = ({ - required Uri remoteVmServiceUri, - Uri? serviceUri, - bool enableAuthCodes = true, - bool serveDevTools = false, - Uri? devToolsServerAddress, - bool enableServicePortFallback = false, - List cachedUserTags = const [], - String? dartExecutable, - String? google3WorkspaceRoot, - }) { - expect(remoteVmServiceUri, Uri(scheme: 'foo', host: 'bar')); - expect(enableAuthCodes, isTrue); - expect(serviceUri, Uri(scheme: 'http', host: '127.0.0.1', port: 0)); - expect(cachedUserTags, isEmpty); - throw FakeDartDevelopmentServiceException(message: 'No URI'); - }; - final TestFlutterDevice flutterDevice = TestFlutterDevice( - device, - vmServiceUris: Stream.value(testUri), - ); - bool caught = false; - final Completerdone = Completer(); - runZonedGuarded(() { - flutterDevice.connect( - allowExistingDdsInstance: true, - debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug, enableDevTools: false), - ).then((_) => done.complete()); - }, (Object e, StackTrace st) { - expect(e, isA()); - expect((e as StateError).message, contains('No URI')); - expect(testLogger.errorText, contains( - 'DDS has failed to start and there is not an existing DDS instance', - )); - done.complete(); - caught = true; - }); - await done.future; - if (!caught) { - fail('Expected a StateError to be thrown.'); - } - }, overrides: { - VMServiceConnector: () => (Uri httpUri, { - ReloadSources? reloadSources, - Restart? restart, - CompileExpression? compileExpression, - GetSkSLMethod? getSkSLMethod, - FlutterProject? flutterProject, - PrintStructuredErrorLogMethod? printStructuredErrorLogMethod, - io.CompressionOptions compression = io.CompressionOptions.compressionDefault, - Device? device, - required Logger logger, - }) async => FakeVmServiceHost(requests: []).vmService, - })); - testUsingContext('nextPlatform moves through expected platforms', () { expect(nextPlatform('android'), 'iOS'); expect(nextPlatform('iOS'), 'windows'); From 57b0b02e4d7da8c902dc30f81c95dbca8dc325d9 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Thu, 14 Nov 2024 16:45:50 -0800 Subject: [PATCH 082/386] Try running historically flaky tests first to make `flutter build apk` health tests time out more often? (#158967) I have no idea if this will work, but `6_6` is currently the suite that seems to have the most problems. Towards https://github.com/flutter/flutter/issues/158560. --- dev/bots/test.dart | 19 +++++++++++++++++-- dev/bots/utils.dart | 3 +++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/dev/bots/test.dart b/dev/bots/test.dart index 7073a9f3b03..fc659ea1806 100644 --- a/dev/bots/test.dart +++ b/dev/bots/test.dart @@ -236,7 +236,8 @@ Future _runIntegrationToolTests() async { } Future _runFlutterBuildApkHealthTests() async { - final List allTests = Directory(path.join(_toolsPath, 'test', 'flutter_build_apk.shard')) + // Try "priming" the test environment by running historically problematic tests first. + final List toolIntegrationTests = Directory(path.join(_toolsPath, 'test', 'integration.shard')) .listSync(recursive: true).whereType() .map((FileSystemEntity entry) => path.relative(entry.path, from: _toolsPath)) .where((String testPath) => path.basename(testPath).endsWith('_test.dart')).toList(); @@ -244,7 +245,21 @@ Future _runFlutterBuildApkHealthTests() async { await runDartTest( _toolsPath, forceSingleCore: true, - testPaths: selectIndexOfTotalSubshard(allTests), + testPaths: selectIndexOfTotalSubshard(toolIntegrationTests, subshardKey: '6_6'), + collectMetrics: true, + runSkipped: true, + ); + + // Then run the health tests after. + final List flutterBuildApkTests = Directory(path.join(_toolsPath, 'test', 'flutter_build_apk.shard')) + .listSync(recursive: true).whereType() + .map((FileSystemEntity entry) => path.relative(entry.path, from: _toolsPath)) + .where((String testPath) => path.basename(testPath).endsWith('_test.dart')).toList(); + + await runDartTest( + _toolsPath, + forceSingleCore: true, + testPaths: selectIndexOfTotalSubshard(flutterBuildApkTests), collectMetrics: true, ); } diff --git a/dev/bots/utils.dart b/dev/bots/utils.dart index be8ab9b028d..76832ba17a6 100644 --- a/dev/bots/utils.dart +++ b/dev/bots/utils.dart @@ -342,6 +342,7 @@ Future runDartTest(String workingDirectory, { bool ensurePrecompiledTool = true, bool shuffleTests = true, bool collectMetrics = false, + bool runSkipped = false, }) async { int? cpus; final String? cpuVariable = Platform.environment['CPU']; // CPU is set in cirrus.yml @@ -379,6 +380,8 @@ Future runDartTest(String workingDirectory, { '--coverage=$coverage', if (perTestTimeout != null) '--timeout=${perTestTimeout.inMilliseconds}ms', + if (runSkipped) + '--run-skipped', if (testPaths != null) for (final String testPath in testPaths) testPath, From 4ee1ef1262616f5a487b30be8d90df5836385465 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 15 Nov 2024 00:47:00 +0000 Subject: [PATCH 083/386] Bump actions/checkout from 4.2.1 to 4.2.2 (#157473) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [actions/checkout](https://github.com/actions/checkout) from 4.2.1 to 4.2.2.
Release notes

Sourced from actions/checkout's releases.

v4.2.2

What's Changed

Full Changelog: https://github.com/actions/checkout/compare/v4.2.1...v4.2.2

Changelog

Sourced from actions/checkout's changelog.

Changelog

v4.2.2

v4.2.1

v4.2.0

v4.1.7

v4.1.6

v4.1.5

v4.1.4

v4.1.3

v4.1.2

v4.1.1

v4.1.0

... (truncated)

Commits

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=actions/checkout&package-manager=github_actions&previous-version=4.2.1&new-version=4.2.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
--- .github/workflows/coverage.yml | 2 +- .github/workflows/easy-cp.yml | 2 +- .github/workflows/minimal.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index b69803e49fb..319db1980a0 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -19,7 +19,7 @@ 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 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 }} From 6a145094ab4772daa46c4549a8b745c83e46d67d Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Thu, 14 Nov 2024 17:34:49 -0800 Subject: [PATCH 084/386] Further skip `native_assets_test`(s) that runs `flutter build apk`. (#158966) Towards https://github.com/flutter/flutter/issues/158560. Still occurred twice in the last 24h: https://ci.chromium.org/ui/p/flutter/builders/prod/Linux%20tool_integration_tests_6_6/42/overview https://ci.chromium.org/ui/p/flutter/builders/prod/Linux%20tool_integration_tests_6_6/44/overview Let's continue to debug why these are so troublesome, but not block the tree doing so. --- .../test/integration.shard/isolated/native_assets_test.dart | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart b/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart index 5c60634552a..c4fe81939a8 100644 --- a/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart +++ b/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart @@ -220,7 +220,11 @@ void main() { } expectCCompilerIsConfigured(exampleDirectory); }); - }); + }, + // TODO(matanlurey): Debug why flutter build apk often timesout. + // See https://github.com/flutter/flutter/issues/158560 for details. + skip: buildSubcommand == 'apk' ? 'flutter build apk times out' : false, // Temporary workaround for https://github.com/flutter/flutter/issues/158560. + ); } } From eaa99f28b1cebf39be5fe92633d79af0b64fe329 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Thu, 14 Nov 2024 17:38:26 -0800 Subject: [PATCH 085/386] Stop generate both `.kts` and non-`.kts` gradle files for a test project. (#158965) Closes https://github.com/flutter/flutter/issues/158962. --- .../android_plugin_skip_unsupported_test.dart | 49 +++++++++++++++++-- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/packages/flutter_tools/test/integration.shard/android_plugin_skip_unsupported_test.dart b/packages/flutter_tools/test/integration.shard/android_plugin_skip_unsupported_test.dart index 151d0653418..297dc6a725f 100644 --- a/packages/flutter_tools/test/integration.shard/android_plugin_skip_unsupported_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_plugin_skip_unsupported_test.dart @@ -8,6 +8,7 @@ import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/cache.dart'; import '../src/common.dart'; +import 'test_data/deferred_components_config.dart'; import 'test_data/plugin_each_settings_gradle_project.dart'; import 'test_data/plugin_project.dart'; import 'test_data/project.dart'; @@ -114,12 +115,34 @@ void main() { test( 'skip plugin with android folder if it does not support the Android platform', () async { - final Project project = PluginWithPathAndroidProject(); + final Project project = PluginWithPathAndroidProjectWithoutDeferred(); final ProcessResult buildApkResult = await testUnsupportedPlugin( project: project, createAndroidPluginFolder: true); expect(buildApkResult.stderr.toString(), isNot(contains('Please fix your settings.gradle'))); expect(buildApkResult, const ProcessResultMatcher()); + + // Regression check for https://github.com/flutter/flutter/issues/158962. + { + final Directory androidDir = project.dir.childDirectory('android'); + expect( + androidDir.childFile('settings.gradle.kts'), + exists, + reason: + 'Modern flutter create --platforms android template creates this', + ); + expect( + androidDir.childFile('settings.gradle'), + isNot(exists), + reason: '' + 'flutter create should have created a settings.gradle.kts file ' + 'but not a settings.gradle file. Prior to the change in the PR ' + 'addressing https://github.com/flutter/flutter/issues/158962 ' + 'both files were created, which means that tooling picked one ' + 'and not the other, which causes ambiguity for debugging test ' + 'flakes.', + ); + } }); // TODO(54566): Remove test when issue is resolved. @@ -186,13 +209,31 @@ dependencies: path: ../ '''; +/// Project that load's a plugin from the specified path. +class PluginWithPathAndroidProjectWithoutDeferred extends PluginProject { + // Intentionally omit; this test case has nothing to do with deferred + // components and a DefererdComponentsConfig will cause duplicates of files + // such as build.gradle{.kts}, settings.gradle{kts} and related to be + // generated, which in turn adds ambiguity to how the tests are built and + // executed. + // + // See https://github.com/flutter/flutter/issues/158962. + @override + DeferredComponentsConfig? get deferredComponents => null; + + @override + String get pubspec => pubspecWithPluginPath; +} + /// Project that load's a plugin from the specified path. class PluginWithPathAndroidProject extends PluginProject { @override String get pubspec => pubspecWithPluginPath; } -// TODO(54566): Remove class when issue is resolved. +// TODO(matanlurey): Remove class when `.flutter-plugins` is no longer emitted. +// See https://github.com/flutter/flutter/issues/48918. + /// [PluginEachSettingsGradleProject] that load's a plugin from the specified /// path. class PluginEachWithPathAndroidProject extends PluginEachSettingsGradleProject { @@ -200,7 +241,9 @@ class PluginEachWithPathAndroidProject extends PluginEachSettingsGradleProject { String get pubspec => pubspecWithPluginPath; } -// TODO(54566): Remove class when issue is resolved. +// TODO(matanlurey): Remove class when `.flutter-plugins` is no longer emitted. +// See https://github.com/flutter/flutter/issues/48918. + /// [PluginCompromisedEachSettingsGradleProject] that load's a plugin from the /// specified path. class PluginCompromisedEachWithPathAndroidProject From 256359194e2b6efbf0cd7148661125bd1a68f5d5 Mon Sep 17 00:00:00 2001 From: Martin Kustermann Date: Fri, 15 Nov 2024 15:05:42 +0100 Subject: [PATCH 086/386] Fix duplicate work in native assets release builds (#158980) In release builds linking of native assets is enabled. The build step is only a temprary step, it's output is given to the link step which then returns all final assets (effectively a map-reduce system). Assets that aren't sent to a specific linker could be conceptually viewed as sent to a linker that will emit it's input as-is. => The code currently took output of build & link step and therefore accumulated assets that aren't explicitly sent to a linker twice. => This led to performing work twice for those (e.g. copying them twice) This PR changes this such that if linking mode is enabled, we only rely on the output of the link phase. That in return means many tests that mock the native asset builds need to be updated to mock the output of the link phase. --- .../isolated/native_assets/native_assets.dart | 5 +- .../isolated/android/native_assets_test.dart | 25 +++++--- .../targets/native_assets_test.dart | 50 ++++++++------- .../fake_native_assets_build_runner.dart | 38 ++++++++++- .../isolated/ios/native_assets_test.dart | 44 +++++++------ .../isolated/macos/native_assets_test.dart | 43 +++++++------ .../isolated/native_assets_test.dart | 63 +++++++++++++++++++ .../isolated/windows/native_assets_test.dart | 26 ++++---- 8 files changed, 207 insertions(+), 87 deletions(-) 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..a6b36b00e01 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 @@ -750,9 +750,10 @@ 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() diff --git a/packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart index 1b3c95a9eb8..d6303637f30 100644 --- a/packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart @@ -67,21 +67,26 @@ void main() { final File dylibAfterCompiling = fileSystem.file('libbar.so'); // The mock doesn't create the file, so create it here. await dylibAfterCompiling.create(); + + final List codeAssets = [ + CodeAsset( + package: 'bar', + name: 'bar.dart', + linkMode: DynamicLoadingBundled(), + os: OS.android, + architecture: Architecture.arm64, + file: Uri.file('libbar.so'), + ), + ]; final FakeFlutterNativeAssetsBuildRunner buildRunner = FakeFlutterNativeAssetsBuildRunner( packagesWithNativeAssetsResult: [ Package('bar', projectUri), ], buildResult: FakeFlutterNativeAssetsBuilderResult.fromAssets( - codeAssets: [ - CodeAsset( - package: 'bar', - name: 'bar.dart', - linkMode: DynamicLoadingBundled(), - os: OS.android, - architecture: Architecture.arm64, - file: Uri.file('libbar.so'), - ), - ], + codeAssets: codeAssets, + ), + linkResult: FakeFlutterNativeAssetsBuilderResult.fromAssets( + codeAssets: codeAssets, ), ); await runFlutterSpecificDartBuild( diff --git a/packages/flutter_tools/test/general.shard/isolated/build_system/targets/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/build_system/targets/native_assets_test.dart index 367e8708092..ad1decb6eaf 100644 --- a/packages/flutter_tools/test/general.shard/isolated/build_system/targets/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/build_system/targets/native_assets_test.dart @@ -190,23 +190,27 @@ void main() { () async { await createPackageConfig(iosEnvironment); + final List codeAssets = [ + CodeAsset( + package: 'foo', + name: 'foo.dart', + linkMode: DynamicLoadingBundled(), + os: OS.iOS, + architecture: Architecture.arm64, + file: Uri.file('foo.framework/foo'), + ), + ]; final FlutterNativeAssetsBuildRunner buildRunner = FakeFlutterNativeAssetsBuildRunner( packagesWithNativeAssetsResult: [Package('foo', iosEnvironment.buildDir.uri)], buildResult: FakeFlutterNativeAssetsBuilderResult.fromAssets( - codeAssets: [ - CodeAsset( - package: 'foo', - name: 'foo.dart', - linkMode: DynamicLoadingBundled(), - os: OS.iOS, - architecture: Architecture.arm64, - file: Uri.file('foo.framework/foo'), - ), - ], + codeAssets: codeAssets, dependencies: [ Uri.file('src/foo.c'), ], ), + linkResult: FakeFlutterNativeAssetsBuilderResult.fromAssets( + codeAssets: codeAssets, + ), ); await NativeAssets(buildRunner: buildRunner).build(iosEnvironment); @@ -252,26 +256,30 @@ void main() { await createPackageConfig(androidEnvironment); await fileSystem.file('libfoo.so').create(); + final List codeAssets = [ + if (hasAssets) + CodeAsset( + package: 'foo', + name: 'foo.dart', + linkMode: DynamicLoadingBundled(), + os: OS.android, + architecture: Architecture.arm64, + file: Uri.file('libfoo.so'), + ), + ]; final FakeFlutterNativeAssetsBuildRunner buildRunner = FakeFlutterNativeAssetsBuildRunner( packagesWithNativeAssetsResult: [ Package('foo', androidEnvironment.buildDir.uri) ], buildResult: FakeFlutterNativeAssetsBuilderResult.fromAssets( - codeAssets: [ - if (hasAssets) - CodeAsset( - package: 'foo', - name: 'foo.dart', - linkMode: DynamicLoadingBundled(), - os: OS.android, - architecture: Architecture.arm64, - file: Uri.file('libfoo.so'), - ), - ], + codeAssets: codeAssets, dependencies: [ Uri.file('src/foo.c'), ], ), + linkResult: FakeFlutterNativeAssetsBuilderResult.fromAssets( + codeAssets: codeAssets, + ), ); await NativeAssets(buildRunner: buildRunner).build(androidEnvironment); expect( diff --git a/packages/flutter_tools/test/general.shard/isolated/fake_native_assets_build_runner.dart b/packages/flutter_tools/test/general.shard/isolated/fake_native_assets_build_runner.dart index 870fb945766..e8dc48bfe3a 100644 --- a/packages/flutter_tools/test/general.shard/isolated/fake_native_assets_build_runner.dart +++ b/packages/flutter_tools/test/general.shard/isolated/fake_native_assets_build_runner.dart @@ -12,6 +12,8 @@ import 'package:native_assets_builder/native_assets_builder.dart'; import 'package:native_assets_cli/code_assets_builder.dart'; import 'package:package_config/package_config_types.dart'; +export 'package:native_assets_cli/code_assets_builder.dart' show CodeAsset, DynamicLoadingBundled; + /// Mocks all logic instead of using `package:native_assets_builder`, which /// relies on doing process calls to `pub` and the local file system. class FakeFlutterNativeAssetsBuildRunner @@ -20,6 +22,7 @@ class FakeFlutterNativeAssetsBuildRunner this.hasPackageConfigResult = true, this.packagesWithNativeAssetsResult = const [], this.onBuild, + this.onLink, this.buildDryRunResult = const FakeFlutterNativeAssetsBuilderResult(), this.buildResult = const FakeFlutterNativeAssetsBuilderResult(), this.linkResult = const FakeFlutterNativeAssetsBuilderResult(), @@ -30,6 +33,7 @@ class FakeFlutterNativeAssetsBuildRunner ndkCCompilerConfigResult ?? CCompilerConfig(); final BuildResult? Function(BuildConfig)? onBuild; + final LinkResult? Function(LinkConfig)? onLink; final BuildResult? buildResult; final LinkResult? linkResult; final BuildDryRunResult? buildDryRunResult; @@ -99,11 +103,29 @@ class FakeFlutterNativeAssetsBuildRunner required Uri workingDirectory, required BuildResult buildResult, }) async { - for (final Package _ in packagesWithNativeAssetsResult) { + LinkResult? result = linkResult; + for (final Package package in packagesWithNativeAssetsResult) { + final LinkConfigBuilder configBuilder = configCreator() + ..setupHookConfig( + packageRoot: package.root, + packageName: package.name, + targetOS: targetOS, + supportedAssetTypes: supportedAssetTypes, + buildMode: buildMode, + ) + ..setupLinkRunConfig( + outputDirectory: Uri.parse('build-out-dir'), + outputDirectoryShared: Uri.parse('build-out-dir-shared'), + recordedUsesFile: null, + ); + final LinkConfig buildConfig = LinkConfig(configBuilder.json); + if (onLink != null) { + result = onLink!(buildConfig); + } lastBuildMode = buildMode; linkInvocations++; } - return linkResult; + return result; } @override @@ -148,12 +170,22 @@ final class FakeFlutterNativeAssetsBuilderResult factory FakeFlutterNativeAssetsBuilderResult.fromAssets({ List codeAssets = const [], + Map> codeAssetsForLinking = const >{}, List dependencies = const [], }) { return FakeFlutterNativeAssetsBuilderResult( encodedAssets: [ for (final CodeAsset codeAsset in codeAssets) codeAsset.encode(), - ], dependencies: dependencies); + ], + encodedAssetsForLinking: >{ + for (final String linkerName in codeAssetsForLinking.keys) + linkerName: [ + for (final CodeAsset codeAsset in codeAssetsForLinking[linkerName]!) + codeAsset.encode(), + ], + }, + dependencies: dependencies, + ); } @override diff --git a/packages/flutter_tools/test/general.shard/isolated/ios/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/ios/native_assets_test.dart index 0a3c7a1a4f2..705210cdbe9 100644 --- a/packages/flutter_tools/test/general.shard/isolated/ios/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/ios/native_assets_test.dart @@ -162,31 +162,35 @@ void main() { final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.yaml').uri; await packageConfig.parent.create(); await packageConfig.create(); + + List codeAssets(OS targetOS, CodeConfig codeConfig) => [ + CodeAsset( + package: 'bar', + name: 'bar.dart', + linkMode: DynamicLoadingBundled(), + os: targetOS, + architecture: codeConfig.targetArchitecture, + file: Uri.file('${codeConfig.targetArchitecture}/libbar.dylib'), + ), + CodeAsset( + package: 'buz', + name: 'buz.dart', + linkMode: DynamicLoadingBundled(), + os: targetOS, + architecture: codeConfig.targetArchitecture, + file: Uri.file('${codeConfig.targetArchitecture}/libbuz.dylib'), + ), + ]; final FakeFlutterNativeAssetsBuildRunner buildRunner = FakeFlutterNativeAssetsBuildRunner( packagesWithNativeAssetsResult: [ Package('bar', projectUri), ], onBuild: (BuildConfig config) => - FakeFlutterNativeAssetsBuilderResult.fromAssets( - codeAssets: [ - CodeAsset( - package: 'bar', - name: 'bar.dart', - linkMode: DynamicLoadingBundled(), - os: config.targetOS, - architecture: config.codeConfig.targetArchitecture, - file: Uri.file('${config.codeConfig.targetArchitecture}/libbar.dylib'), - ), - CodeAsset( - package: 'buz', - name: 'buz.dart', - linkMode: DynamicLoadingBundled(), - os: config.targetOS, - architecture: config.codeConfig.targetArchitecture, - file: Uri.file('${config.codeConfig.targetArchitecture}/libbuz.dylib'), - ), - ], - ), + FakeFlutterNativeAssetsBuilderResult.fromAssets(codeAssets: codeAssets(config.targetOS, config.codeConfig)), + onLink: (LinkConfig config) => + buildMode == BuildMode.debug + ? null + : FakeFlutterNativeAssetsBuilderResult.fromAssets(codeAssets: codeAssets(config.targetOS, config.codeConfig)), ); await runFlutterSpecificDartBuild( environmentDefines: { diff --git a/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_test.dart index dfbf8987fa2..524cb733ecc 100644 --- a/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_test.dart @@ -268,31 +268,34 @@ void main() { final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.yaml').uri; await packageConfig.parent.create(); await packageConfig.create(); + + List codeAssets(OS targetOS, CodeConfig codeConfig) => [ + CodeAsset( + package: 'bar', + name: 'bar.dart', + linkMode: DynamicLoadingBundled(), + os: targetOS, + architecture: codeConfig.targetArchitecture, + file: Uri.file('${codeConfig.targetArchitecture}/libbar.dylib'), + ), + CodeAsset( + package: 'buz', + name: 'buz.dart', + linkMode: DynamicLoadingBundled(), + os: targetOS, + architecture: codeConfig.targetArchitecture, + file: Uri.file('${codeConfig.targetArchitecture}/libbuz.dylib'), + ), + ]; final FakeFlutterNativeAssetsBuildRunner buildRunner = FakeFlutterNativeAssetsBuildRunner( packagesWithNativeAssetsResult: [ Package('bar', projectUri), ], onBuild: (BuildConfig config) => - FakeFlutterNativeAssetsBuilderResult.fromAssets( - codeAssets: [ - CodeAsset( - package: 'bar', - name: 'bar.dart', - linkMode: DynamicLoadingBundled(), - os: config.targetOS, - architecture: config.codeConfig.targetArchitecture, - file: Uri.file('${config.codeConfig.targetArchitecture}/libbar.dylib'), - ), - CodeAsset( - package: 'buz', - name: 'buz.dart', - linkMode: DynamicLoadingBundled(), - os: config.targetOS, - architecture: config.codeConfig.targetArchitecture, - file: Uri.file('${config.codeConfig.targetArchitecture}/libbuz.dylib'), - ), - ], - ), + FakeFlutterNativeAssetsBuilderResult.fromAssets(codeAssets: codeAssets(config.targetOS, config.codeConfig)), + onLink: (LinkConfig config) => buildMode == BuildMode.debug + ? null + : FakeFlutterNativeAssetsBuilderResult.fromAssets(codeAssets: codeAssets(config.targetOS, config.codeConfig)), ); final (_, Uri nativeAssetsYaml) = await runFlutterSpecificDartBuild( environmentDefines: { diff --git a/packages/flutter_tools/test/general.shard/isolated/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/native_assets_test.dart index c8beb0813d2..dbb720d5ca6 100644 --- a/packages/flutter_tools/test/general.shard/isolated/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/native_assets_test.dart @@ -300,4 +300,67 @@ void main() { ), ); }); + + testUsingContext('Native assets: no duplicate assets with linking', overrides: { + FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), + ProcessManager: () => FakeProcessManager.empty(), + }, () async { + final File packageConfig = + environment.projectDir.childFile('.dart_tool/package_config.json'); + final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.yaml').uri; + await packageConfig.parent.create(); + await packageConfig.create(); + + final File directSoFile = environment.projectDir.childFile('direct.so'); + directSoFile.writeAsBytesSync([]); + final File linkableAFile = environment.projectDir.childFile('linkable.a'); + linkableAFile.writeAsBytesSync([]); + final File linkedSoFile = environment.projectDir.childFile('linked.so'); + linkedSoFile.writeAsBytesSync([]); + + CodeAsset makeCodeAsset(String name, Uri file, LinkMode linkMode) + => CodeAsset( + package: 'bar', + name: name, + linkMode: linkMode, + os: OS.linux, + architecture: Architecture.x64, + file: file, + ); + + final (DartBuildResult result, _) = await runFlutterSpecificDartBuild( + environmentDefines: { + // Release mode means the dart build has linking enabled. + kBuildMode: BuildMode.release.cliName, + }, + targetPlatform: TargetPlatform.linux_x64, + projectUri: projectUri, + nativeAssetsYamlUri: nonFlutterTesterAssetUri, + fileSystem: fileSystem, + buildRunner: FakeFlutterNativeAssetsBuildRunner( + packagesWithNativeAssetsResult: [ + Package('bar', projectUri), + ], + buildResult: FakeFlutterNativeAssetsBuilderResult.fromAssets( + codeAssets: [ + makeCodeAsset('direct', directSoFile.uri, DynamicLoadingBundled()), + ], + codeAssetsForLinking: >{ + 'package:bar' : [ + makeCodeAsset('linkable', linkableAFile.uri, StaticLinking()), + ], + }, + ), + linkResult: FakeFlutterNativeAssetsBuilderResult.fromAssets( + codeAssets: [ + makeCodeAsset('direct', directSoFile.uri, DynamicLoadingBundled()), + makeCodeAsset('linked', linkedSoFile.uri, DynamicLoadingBundled()), + ], + ), + ), + ); + expect( + result.codeAssets.map((CodeAsset c) => c.file!.toString()).toList()..sort(), + [directSoFile.uri.toString(), linkedSoFile.uri.toString()]); + }); } diff --git a/packages/flutter_tools/test/general.shard/isolated/windows/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/windows/native_assets_test.dart index b3a6bca1a45..ad0658a1ee3 100644 --- a/packages/flutter_tools/test/general.shard/isolated/windows/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/windows/native_assets_test.dart @@ -77,21 +77,25 @@ void main() { final File dylibAfterCompiling = fileSystem.file('bar.dll'); // The mock doesn't create the file, so create it here. await dylibAfterCompiling.create(); + + final List codeAssets = [ + CodeAsset( + package: 'bar', + name: 'bar.dart', + linkMode: DynamicLoadingBundled(), + os: OS.windows, + architecture: Architecture.x64, + file: dylibAfterCompiling.uri, + ), + ]; final FakeFlutterNativeAssetsBuildRunner buildRunner = FakeFlutterNativeAssetsBuildRunner( packagesWithNativeAssetsResult: [ Package('bar', projectUri), ], - buildResult: FakeFlutterNativeAssetsBuilderResult.fromAssets( - codeAssets: [ - CodeAsset( - package: 'bar', - name: 'bar.dart', - linkMode: DynamicLoadingBundled(), - os: OS.windows, - architecture: Architecture.x64, - file: dylibAfterCompiling.uri, - ), - ], + buildResult: FakeFlutterNativeAssetsBuilderResult.fromAssets(codeAssets: codeAssets), + linkResult: buildMode == BuildMode.debug + ? null + : FakeFlutterNativeAssetsBuilderResult.fromAssets(codeAssets: codeAssets, ), ); final (_, Uri nativeAssetsYaml) = await runFlutterSpecificDartBuild( From 1636fbd4cbdf09ba3638de4d7c2eabc84bc933e2 Mon Sep 17 00:00:00 2001 From: Martin Kustermann Date: Fri, 15 Nov 2024 16:23:23 +0100 Subject: [PATCH 087/386] Fix code asset copying logic in native asset code (#158984) After the dart build is done, the flutter tool has to bundle the produced shared libraries, which it does that by copying them around. Though the code assumed that all code assets are shared libraries to be bundled, whereas in fact one can have code assets without any actual code (ones that are installed on the target system already or artificial code assets whose symbols get resolved from executable / process). => Using non-bundled code assets currently results in null pointer exceptions and/or cast errors. => We update the copy code to only operate on code assets that have a shared library to bundle. We also update the copy routines by removing copy&past'ed - but slightly different - printing code into the shared caller function. --- .../native_assets/android/native_assets.dart | 45 ++--- .../native_assets/ios/native_assets.dart | 69 +++---- .../native_assets/macos/native_assets.dart | 183 ++++++++---------- .../isolated/native_assets/native_assets.dart | 44 +++-- .../isolated/native_assets_test.dart | 48 +++++ 5 files changed, 212 insertions(+), 177 deletions(-) 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..fb3634365dc 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,30 +20,26 @@ 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); + 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); } } 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..76842bcd8fb 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 @@ -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..700157416fa 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,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 'native_assets_host.dart'; // TODO(dcharkes): Fetch minimum MacOS version from somewhere. https://github.com/flutter/flutter/issues/145104 @@ -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 a6b36b00e01..f50fb43389d 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 @@ -629,6 +629,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 +688,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. @@ -908,22 +924,18 @@ 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); + + 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); } } diff --git a/packages/flutter_tools/test/general.shard/isolated/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/native_assets_test.dart index dbb720d5ca6..dce1d3187f4 100644 --- a/packages/flutter_tools/test/general.shard/isolated/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/native_assets_test.dart @@ -180,6 +180,54 @@ void main() { expect(buildRunner.buildDryRunInvocations, 1); }); + testUsingContext('Native assets: non-bundled libraries require no copying', overrides: { + FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), + ProcessManager: () => FakeProcessManager.empty(), + }, () async { + final File packageConfig = + environment.projectDir.childFile('.dart_tool/package_config.json'); + final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.yaml').uri; + await packageConfig.parent.create(); + await packageConfig.create(); + + final File directSoFile = environment.projectDir.childFile('direct.so'); + directSoFile.writeAsBytesSync([]); + + CodeAsset makeCodeAsset(String name, LinkMode linkMode, [Uri? file]) + => CodeAsset( + package: 'bar', + name: name, + linkMode: linkMode, + os: OS.linux, + architecture: Architecture.x64, + file: file, + ); + + final List codeAssets = [ + makeCodeAsset('malloc', LookupInProcess()), + makeCodeAsset('free', LookupInExecutable()), + makeCodeAsset('draw', DynamicLoadingSystem(Uri.file('/usr/lib/skia.so'))), + ]; + + await runFlutterSpecificDartBuild( + environmentDefines: { + kBuildMode: BuildMode.release.cliName, + }, + targetPlatform: TargetPlatform.linux_x64, + projectUri: projectUri, + nativeAssetsYamlUri: nonFlutterTesterAssetUri, + fileSystem: fileSystem, + buildRunner: FakeFlutterNativeAssetsBuildRunner( + packagesWithNativeAssetsResult: [ + Package('bar', projectUri), + ], + buildResult: FakeFlutterNativeAssetsBuilderResult.fromAssets(codeAssets: codeAssets), + linkResult: FakeFlutterNativeAssetsBuilderResult.fromAssets(codeAssets: codeAssets), + ), + ); + expect(testLogger.traceText, isNot(contains('Copying native assets to'))); + }); + testUsingContext('build with assets but not enabled', overrides: { ProcessManager: () => FakeProcessManager.empty(), }, () async { From c4c8f6d2bd79d030650dec4e62a3620dbd595049 Mon Sep 17 00:00:00 2001 From: Jenn Magder Date: Fri, 15 Nov 2024 07:27:24 -0800 Subject: [PATCH 088/386] Label PRs with gradle and Android paths "platform-android" (#158970) Fixes https://github.com/flutter/flutter/issues/158951 --- .github/labeler.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/labeler.yml b/.github/labeler.yml index f2aff1e0b61..c83124b35de 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -136,6 +136,8 @@ platform-android: - changed-files: - any-glob-to-any-file: - docs/platform/android/**/* + - packages/flutter_tools/lib/src/android/**/* + - packages/flutter_tools/gradle/**/* platform-ios: - changed-files: From 0e2d55e0e7b2ebb8003ebb6519f43006f758b36f Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Fri, 15 Nov 2024 10:44:07 -0500 Subject: [PATCH 089/386] Roll Packages from b9ac917daeb0 to b164be312ca2 (4 revisions) (#158986) https://github.com/flutter/packages/compare/b9ac917daeb0...b164be312ca2 2024-11-14 magder@google.com Remove packages/platform from dependabot config (flutter/packages#8099) 2024-11-14 magder@google.com Ignore dependabot minor and patch updates of Kotlin mocking library (flutter/packages#8056) 2024-11-14 paulberry@google.com [google_identity_services_web] Set nonce properly in loadWebSdk(). (flutter/packages#8069) 2024-11-14 engine-flutter-autoroll@skia.org Roll Flutter (stable) from 603104015dd6 to dec2ee5c1f98 (4 revisions) (flutter/packages#8084) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-packages-flutter-autoroll Please CC flutter-ecosystem@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/flutter_packages.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/flutter_packages.version b/bin/internal/flutter_packages.version index 9898825b991..3bedfae07be 100644 --- a/bin/internal/flutter_packages.version +++ b/bin/internal/flutter_packages.version @@ -1 +1 @@ -b9ac917daeb0fbf5bd6ad4a7d2a69ab81749d767 +b164be312ca2e45ea332e38dd278ac84abe7658f From 09941e7b4781b81adeb7bce8b389e5b8b45325ca Mon Sep 17 00:00:00 2001 From: Mouad Debbar Date: Fri, 15 Nov 2024 11:24:20 -0500 Subject: [PATCH 090/386] [web] Remove the benchmarks of the HTML renderer (#158520) As the title says, this PR deletes the HTML renderer's benchmarks. --- .ci.yaml | 17 ----- TESTOWNERS | 1 - dev/benchmarks/macrobenchmarks/README.md | 8 +- .../lib/src/web/bench_child_layers.dart | 3 +- .../lib/src/web/bench_image_decoding.dart | 4 - .../lib/src/web/bench_text_layout.dart | 75 ++----------------- .../macrobenchmarks/lib/src/web/recorder.dart | 4 +- .../macrobenchmarks/lib/web_benchmarks.dart | 22 +----- .../bin/tasks/web_benchmarks_canvaskit.dart | 1 - .../bin/tasks/web_benchmarks_html.dart | 17 ----- .../bin/tasks/web_benchmarks_skwasm.dart | 1 - .../bin/tasks/web_benchmarks_skwasm_st.dart | 1 - dev/devicelab/lib/tasks/web_benchmarks.dart | 8 +- 13 files changed, 17 insertions(+), 145 deletions(-) delete mode 100644 dev/devicelab/bin/tasks/web_benchmarks_html.dart diff --git a/.ci.yaml b/.ci.yaml index 83183f33557..1fa2ef0546e 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -1541,23 +1541,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 diff --git a/TESTOWNERS b/TESTOWNERS index 57a180a3e26..44da941b0f3 100644 --- a/TESTOWNERS +++ b/TESTOWNERS @@ -290,7 +290,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 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/lib/src/web/bench_child_layers.dart b/dev/benchmarks/macrobenchmarks/lib/src/web/bench_child_layers.dart index 4a82f43f4cf..24b9d6592d8 100644 --- a/dev/benchmarks/macrobenchmarks/lib/src/web/bench_child_layers.dart +++ b/dev/benchmarks/macrobenchmarks/lib/src/web/bench_child_layers.dart @@ -9,8 +9,7 @@ import 'recorder.dart'; /// Repeatedly paints a grid of rectangles where each rectangle is drawn in its /// own [Picture]. /// -/// Measures the performance of updating many layers. For example, the HTML -/// rendering backend attempts to reuse the DOM nodes created for engine layers. +/// Measures the performance of updating many layers. /// /// See also `bench_draw_rect.dart`, which draws nearly identical UI but puts all /// rectangles into the same picture. diff --git a/dev/benchmarks/macrobenchmarks/lib/src/web/bench_image_decoding.dart b/dev/benchmarks/macrobenchmarks/lib/src/web/bench_image_decoding.dart index 1bc691ea850..32047dd5e27 100644 --- a/dev/benchmarks/macrobenchmarks/lib/src/web/bench_image_decoding.dart +++ b/dev/benchmarks/macrobenchmarks/lib/src/web/bench_image_decoding.dart @@ -18,10 +18,6 @@ import 'recorder.dart'; // WASM codecs execute on the main thread and block the UI, leading to jank, // but the browser's WebCodecs API is asynchronous running on a separate thread // and does not jank. However, the benchmark result may be the same. -// -// This benchmark does not support the HTML renderer because the HTML renderer -// cannot decode image frames (it always returns 1 dummy frame, even for -// animated images). class BenchImageDecoding extends RawRecorder { BenchImageDecoding() : super( name: benchmarkName, diff --git a/dev/benchmarks/macrobenchmarks/lib/src/web/bench_text_layout.dart b/dev/benchmarks/macrobenchmarks/lib/src/web/bench_text_layout.dart index 6788ec8b712..bebbbf54bea 100644 --- a/dev/benchmarks/macrobenchmarks/lib/src/web/bench_text_layout.dart +++ b/dev/benchmarks/macrobenchmarks/lib/src/web/bench_text_layout.dart @@ -45,27 +45,13 @@ class ParagraphGenerator { } } -/// Which mode to run [BenchBuildColorsGrid] in. -enum _TestMode { - /// Uses the HTML rendering backend with the canvas 2D text layout. - useCanvasTextLayout, - - /// Uses CanvasKit for everything. - useCanvasKit, -} - /// Repeatedly lays out a paragraph. /// /// Creates a different paragraph each time in order to avoid hitting the cache. class BenchTextLayout extends RawRecorder { - BenchTextLayout.canvas() - : super(name: canvasBenchmarkName); + BenchTextLayout() : super(name: benchmarkName); - BenchTextLayout.canvasKit() - : super(name: canvasKitBenchmarkName); - - static const String canvasBenchmarkName = 'text_canvas_layout'; - static const String canvasKitBenchmarkName = 'text_canvaskit_layout'; + static const String benchmarkName = 'text_canvaskit_layout'; final ParagraphGenerator generator = ParagraphGenerator(); @@ -143,14 +129,9 @@ class BenchTextLayout extends RawRecorder { /// use the same paragraph instance because the layout method will shortcircuit /// in that case. class BenchTextCachedLayout extends RawRecorder { - BenchTextCachedLayout.canvas() - : super(name: canvasBenchmarkName); + BenchTextCachedLayout() : super(name: benchmarkName); - BenchTextCachedLayout.canvasKit() - : super(name: canvasKitBenchmarkName); - - static const String canvasBenchmarkName = 'text_canvas_cached_layout'; - static const String canvasKitBenchmarkName = 'text_canvas_kit_cached_layout'; + static const String benchmarkName = 'text_canvas_kit_cached_layout'; @override void body(Profile profile) { @@ -179,11 +160,7 @@ int _counter = 0; /// The benchmark constructs a tabbed view, where each tab displays a list of /// colors. Each color's description is made of several [Text] nodes. class BenchBuildColorsGrid extends WidgetBuildRecorder { - BenchBuildColorsGrid.canvas() - : _mode = _TestMode.useCanvasTextLayout, super(name: canvasBenchmarkName); - - BenchBuildColorsGrid.canvasKit() - : _mode = _TestMode.useCanvasKit, super(name: canvasKitBenchmarkName); + BenchBuildColorsGrid() : super(name: benchmarkName); /// Disables tracing for this benchmark. /// @@ -193,47 +170,7 @@ class BenchBuildColorsGrid extends WidgetBuildRecorder { @override bool get isTracingEnabled => 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..d396ba63db0 100644 --- a/dev/benchmarks/macrobenchmarks/lib/web_benchmarks.dart +++ b/dev/benchmarks/macrobenchmarks/lib/web_benchmarks.dart @@ -36,7 +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. @@ -80,24 +79,11 @@ final Map benchmarks = { 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/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/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); From 32133ce7acdf0c98c02301eca8cd3820c977e7f7 Mon Sep 17 00:00:00 2001 From: "auto-submit[bot]" <98614782+auto-submit[bot]@users.noreply.github.com> Date: Fri, 15 Nov 2024 19:05:47 +0000 Subject: [PATCH 091/386] Reverts "Try running historically flaky tests first to make `flutter build apk` health tests time out more often? (#158967)" (#158993) Reverts: flutter/flutter#158967 Initiated by: matanlurey Reason for reverting: `--run-skipped` doesn't work in this repository (https://github.com/flutter/flutter/issues/158972). Original PR Author: matanlurey Reviewed By: {andrewkolos} This change reverts the following previous change: I have no idea if this will work, but `6_6` is currently the suite that seems to have the most problems. Towards https://github.com/flutter/flutter/issues/158560. --- dev/bots/test.dart | 19 ++----------------- dev/bots/utils.dart | 3 --- 2 files changed, 2 insertions(+), 20 deletions(-) diff --git a/dev/bots/test.dart b/dev/bots/test.dart index fc659ea1806..7073a9f3b03 100644 --- a/dev/bots/test.dart +++ b/dev/bots/test.dart @@ -236,8 +236,7 @@ Future _runIntegrationToolTests() async { } Future _runFlutterBuildApkHealthTests() async { - // Try "priming" the test environment by running historically problematic tests first. - final List toolIntegrationTests = Directory(path.join(_toolsPath, 'test', 'integration.shard')) + final List allTests = Directory(path.join(_toolsPath, 'test', 'flutter_build_apk.shard')) .listSync(recursive: true).whereType() .map((FileSystemEntity entry) => path.relative(entry.path, from: _toolsPath)) .where((String testPath) => path.basename(testPath).endsWith('_test.dart')).toList(); @@ -245,21 +244,7 @@ Future _runFlutterBuildApkHealthTests() async { await runDartTest( _toolsPath, forceSingleCore: true, - testPaths: selectIndexOfTotalSubshard(toolIntegrationTests, subshardKey: '6_6'), - collectMetrics: true, - runSkipped: true, - ); - - // Then run the health tests after. - final List flutterBuildApkTests = Directory(path.join(_toolsPath, 'test', 'flutter_build_apk.shard')) - .listSync(recursive: true).whereType() - .map((FileSystemEntity entry) => path.relative(entry.path, from: _toolsPath)) - .where((String testPath) => path.basename(testPath).endsWith('_test.dart')).toList(); - - await runDartTest( - _toolsPath, - forceSingleCore: true, - testPaths: selectIndexOfTotalSubshard(flutterBuildApkTests), + testPaths: selectIndexOfTotalSubshard(allTests), collectMetrics: true, ); } diff --git a/dev/bots/utils.dart b/dev/bots/utils.dart index 76832ba17a6..be8ab9b028d 100644 --- a/dev/bots/utils.dart +++ b/dev/bots/utils.dart @@ -342,7 +342,6 @@ Future runDartTest(String workingDirectory, { bool ensurePrecompiledTool = true, bool shuffleTests = true, bool collectMetrics = false, - bool runSkipped = false, }) async { int? cpus; final String? cpuVariable = Platform.environment['CPU']; // CPU is set in cirrus.yml @@ -380,8 +379,6 @@ Future runDartTest(String workingDirectory, { '--coverage=$coverage', if (perTestTimeout != null) '--timeout=${perTestTimeout.inMilliseconds}ms', - if (runSkipped) - '--run-skipped', if (testPaths != null) for (final String testPath in testPaths) testPath, From 01590aa27ac4d3a904d25ae4c6b792f933a3da6f Mon Sep 17 00:00:00 2001 From: Martin Kustermann Date: Fri, 15 Nov 2024 21:04:42 +0100 Subject: [PATCH 092/386] Refactor native asset integration into flutter tools (#158932) Currently the `NativeAsset` target in flutter tools is responsible for two things: * performing the dart build (in the app as well as all transitive pub dependencies) * taking output (shared libraries) from this build and copying them around This intermingling of responsibilities leads to more complex code and potentially unnecessary work: If the source code changed (e.g. `.c` files change) we have to run the dart build again. But doing so may result in the same shared libraries (e.g. adding comments to the `.c` code). Currently we're going to copy the shared libraries despite them having not changed, which then may cause upstream things to be dirtied (if it's based on timestamp of files) and re-built. Instead this PR splits this `NativeAsset` into the two orthogonal pieces * `DartBuild` target that is responsible for the dart build * `InstallCodeAssets` that is responsible for copying shared libraries to the right place and producing a `native_assets.yaml`. This decoupling is also preparation for a future where a dart build can produce other kinds of assets (e.g. data assets) and is used in the web build as well. (The web build would use `DartBuild` but not `InstalCodeAssets`). --- .../lib/src/build_system/targets/common.dart | 8 +- .../build_system/targets/native_assets.dart | 166 +++++++++++++----- .../isolated/native_assets/native_assets.dart | 114 +++++++----- .../native_assets/test/native_assets.dart | 28 ++- .../build_system/targets/common_test.dart | 5 +- .../isolated/android/native_assets_test.dart | 35 ++-- .../targets/native_assets_test.dart | 58 +++--- .../isolated/ios/native_assets_test.dart | 30 ++-- .../isolated/linux/native_assets_test.dart | 2 - .../isolated/macos/native_assets_test.dart | 41 +++-- .../isolated/native_assets_test.dart | 56 +++--- .../isolated/windows/native_assets_test.dart | 44 +++-- 12 files changed, 372 insertions(+), 215 deletions(-) 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..d9c4243eac0 100644 --- a/packages/flutter_tools/lib/src/build_system/targets/common.dart +++ b/packages/flutter_tools/lib/src/build_system/targets/common.dart @@ -289,7 +289,7 @@ class KernelSnapshotNativeAssets extends Target { @override List get inputs => [ - const Source.pattern('{BUILD_DIR}/native_assets.yaml'), + const Source.pattern('{BUILD_DIR}/${InstallCodeAssets.nativeAssetsFilename}'), ...const KernelSnapshotProgram().inputs, ]; @@ -302,15 +302,15 @@ class KernelSnapshotNativeAssets extends Target { List get depfiles => const []; @override - List get dependencies => [ - const NativeAssets(), + List get dependencies => const [ + InstallCodeAssets(), ]; static const String dillName = 'native_assets.dill'; @override Future build(Environment environment) async { - final File nativeAssetsFile = environment.buildDir.childFile('native_assets.yaml'); + final File nativeAssetsFile = environment.buildDir.childFile(InstallCodeAssets.nativeAssetsFilename); final File dillFile = environment.buildDir.childFile(dillName); final YamlNode nativeAssetContents = loadYamlNode(await nativeAssetsFile.readAsString()); 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..af1a80615d8 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,109 @@ 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 [ + KernelSnapshotProgram(), ]; } + +/// 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. +/// 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. +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.yaml'; + 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/isolated/native_assets/native_assets.dart b/packages/flutter_tools/lib/src/isolated/native_assets/native_assets.dart index f50fb43389d..5c989071564 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 @@ -35,40 +35,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 = getNativeOSFromTargetPlatfrorm(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,22 +93,10 @@ 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 build_info.BuildMode buildMode = _getBuildMode(targetPlatform, environmentDefines, flutterTester); final List targets = flutterTester ? [Target.current] : _targetsForOS(targetPlatform, targetOS, environmentDefines); @@ -105,19 +110,27 @@ Future<(DartBuildResult, Uri)> runFlutterSpecificDartBuild({ buildMode: _nativeAssetsBuildMode(buildMode), fileSystem: fileSystem, targetOS: targetOS); + return result; +} - final String? codesignIdentity = - environmentDefines[build_info.kCodesignIdentity]; +Future installCodeAssets({ + required DartBuildResult dartBuildResult, + required Map environmentDefines, + required build_info.TargetPlatform targetPlatform, + required Uri projectUri, + required FileSystem fileSystem, + required Uri nativeAssetsFileUri, +}) async { + final OS targetOS = getNativeOSFromTargetPlatfrorm(targetPlatform); + final Uri buildUri = nativeAssetsBuildUri(projectUri, targetOS); + final bool flutterTester = targetPlatform == build_info.TargetPlatform.tester; + final build_info.BuildMode buildMode = _getBuildMode(targetPlatform, environmentDefines, flutterTester); - 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); + 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); + final KernelAssets kernelAssets = KernelAssets(assetTargetLocations.values.toList()); + await _writeNativeAssetsYaml(kernelAssets, nativeAssetsFileUri, fileSystem); } Future runFlutterSpecificDartDryRunOnPlatforms({ @@ -142,7 +155,7 @@ Future runFlutterSpecificDartDryRunOnPlatforms({ final bool flutterTester = targetPlatform == build_info.TargetPlatform.tester; - final OS targetOS = _getNativeOSFromTargetPlatfrorm(targetPlatform); + final OS targetOS = getNativeOSFromTargetPlatfrorm(targetPlatform); if (targetOS != OS.macOS && targetOS != OS.windows && targetOS != OS.linux && @@ -162,16 +175,16 @@ Future runFlutterSpecificDartDryRunOnPlatforms({ projectUri: projectUri, fileSystem: fileSystem, targetOS: targetOS); - assetTargetLocations.addAll(_assetTargetLocationsForOS( + assetTargetLocations.addAll(assetTargetLocationsForOS( targetOS, result.codeAssets, flutterTester, buildUri)); } final Uri buildUri = targetPlatforms.length == 1 ? nativeAssetsBuildUri( - projectUri, _getNativeOSFromTargetPlatfrorm(targetPlatforms.single)) + projectUri, getNativeOSFromTargetPlatfrorm(targetPlatforms.single)) : _buildUriMultiple(projectUri); final Uri nativeAssetsYamlUri = buildUri.resolve('native_assets.yaml'); - await writeNativeAssetsYaml( + await _writeNativeAssetsYaml( KernelAssets(assetTargetLocations.values.toList()), nativeAssetsYamlUri, fileSystem, @@ -405,7 +418,7 @@ class FlutterNativeAssetsBuildRunnerImpl implements FlutterNativeAssetsBuildRunn }(); } -Future writeNativeAssetsYaml( +Future _writeNativeAssetsYaml( KernelAssets assets, Uri nativeAssetsYamlUri, FileSystem fileSystem, @@ -602,7 +615,7 @@ KernelAsset _targetLocationSingleArchitecture( ); } -Map _assetTargetLocationsForOS( +Map assetTargetLocationsForOS( OS targetOS, List codeAssets, bool flutterTester, Uri buildUri) { switch (targetOS) { case OS.windows: @@ -957,7 +970,7 @@ Never _throwNativeAssetsLinkFailed() { ); } -OS _getNativeOSFromTargetPlatfrorm(build_info.TargetPlatform platform) { +OS getNativeOSFromTargetPlatfrorm(build_info.TargetPlatform platform) { switch (platform) { case build_info.TargetPlatform.ios: return OS.iOS; @@ -1083,3 +1096,14 @@ const Map> _osTargets = >{ Architecture.x64, }, }; + +build_info.BuildMode _getBuildMode(build_info.TargetPlatform targetPlatform, 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..679053f0d8c 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.yaml` file which uses absolute + // paths to the shared libraries. + final OS targetOS = getNativeOSFromTargetPlatfrorm(TargetPlatform.tester); + final Uri buildUri = nativeAssetsBuildUri(projectUri, targetOS); + final Uri nativeAssetsFileUri = buildUri.resolve('native_assets.yaml'); + + 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/test/general.shard/build_system/targets/common_test.dart b/packages/flutter_tools/test/general.shard/build_system/targets/common_test.dart index 37f2513c478..40032cc3337 100644 --- a/packages/flutter_tools/test/general.shard/build_system/targets/common_test.dart +++ b/packages/flutter_tools/test/general.shard/build_system/targets/common_test.dart @@ -12,6 +12,7 @@ import 'package:flutter_tools/src/build_system/build_system.dart'; import 'package:flutter_tools/src/build_system/exceptions.dart'; import 'package:flutter_tools/src/build_system/targets/common.dart'; import 'package:flutter_tools/src/build_system/targets/ios.dart'; +import 'package:flutter_tools/src/build_system/targets/native_assets.dart'; import 'package:flutter_tools/src/compile.dart'; import '../../../src/common.dart'; @@ -437,7 +438,7 @@ native-assets: fileSystem.file('.dart_tool/package_config.json') ..createSync(recursive: true) ..writeAsStringSync('{"configVersion": 2, "packages":[]}'); - androidEnvironment.buildDir.childFile('native_assets.yaml') + androidEnvironment.buildDir.childFile(InstallCodeAssets.nativeAssetsFilename) ..createSync(recursive: true) ..writeAsStringSync(empty ? emptyNativeAssets : nonEmptyNativeAssets); final String build = androidEnvironment.buildDir.path; @@ -463,7 +464,7 @@ native-assets: '--output-dill', '$build/native_assets.dill', '--native-assets', - '$build/native_assets.yaml', + '$build/${InstallCodeAssets.nativeAssetsFilename}', '--verbosity=error', '--native-assets-only', ], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'), diff --git a/packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart index d6303637f30..34bfa478b8b 100644 --- a/packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart @@ -13,6 +13,7 @@ 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/build_system/build_system.dart'; +import 'package:flutter_tools/src/build_system/targets/native_assets.dart'; import 'package:flutter_tools/src/features.dart'; import 'package:flutter_tools/src/globals.dart' as globals; import 'package:flutter_tools/src/isolated/native_assets/native_assets.dart'; @@ -59,9 +60,8 @@ void main() { FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), ProcessManager: () => FakeProcessManager.empty(), }, () async { - final File packageConfig = - environment.projectDir.childFile('.dart_tool/package_config.json'); - final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.yaml').uri; + final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); + final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile(InstallCodeAssets.nativeAssetsFilename).uri; await packageConfig.parent.create(); await packageConfig.create(); final File dylibAfterCompiling = fileSystem.file('libbar.so'); @@ -89,17 +89,25 @@ void main() { codeAssets: codeAssets, ), ); - await runFlutterSpecificDartBuild( - environmentDefines: { - kBuildMode: buildMode.cliName, - kMinSdkVersion: minSdkVersion, - }, + final Map environmentDefines = { + kBuildMode: buildMode.cliName, + kMinSdkVersion: minSdkVersion, + }; + final DartBuildResult result = await runFlutterSpecificDartBuild( + environmentDefines: environmentDefines, targetPlatform: TargetPlatform.android_arm64, projectUri: projectUri, - nativeAssetsYamlUri: nonFlutterTesterAssetUri, fileSystem: fileSystem, buildRunner: buildRunner, ); + await installCodeAssets( + dartBuildResult: result, + environmentDefines: environmentDefines, + targetPlatform: TargetPlatform.android_arm64, + projectUri: projectUri, + fileSystem: fileSystem, + nativeAssetsFileUri: nonFlutterTesterAssetUri, + ); expect( (globals.logger as BufferLogger).traceText, stringContainsInOrder([ @@ -108,10 +116,7 @@ void main() { ]), ); - expect( - environment.buildDir.childFile('native_assets.yaml'), - exists, - ); + expect(environment.buildDir.childFile('native_assets.yaml'), exists); expect(buildRunner.buildInvocations, 1); expect( buildRunner.linkInvocations, @@ -130,7 +135,6 @@ void main() { }, () async { final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); - final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.yaml').uri; await packageConfig.create(recursive: true); await runFlutterSpecificDartBuild( environmentDefines: { @@ -138,7 +142,6 @@ void main() { kMinSdkVersion: minSdkVersion, }, targetPlatform: TargetPlatform.android_x64, - nativeAssetsYamlUri: nonFlutterTesterAssetUri, projectUri: projectUri, fileSystem: fileSystem, buildRunner: _BuildRunnerWithoutNdk(), @@ -155,7 +158,6 @@ void main() { }, () async { final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); - final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.yaml').uri; await packageConfig.parent.create(); await packageConfig.create(); expect( @@ -166,7 +168,6 @@ void main() { }, targetPlatform: TargetPlatform.android_arm64, projectUri: projectUri, - nativeAssetsYamlUri: nonFlutterTesterAssetUri, fileSystem: fileSystem, buildRunner: _BuildRunnerWithoutNdk( packagesWithNativeAssetsResult: [ diff --git a/packages/flutter_tools/test/general.shard/isolated/build_system/targets/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/build_system/targets/native_assets_test.dart index ad1decb6eaf..39be84f77f4 100644 --- a/packages/flutter_tools/test/general.shard/isolated/build_system/targets/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/build_system/targets/native_assets_test.dart @@ -68,7 +68,7 @@ void main() { testWithoutContext('NativeAssets throws error if missing target platform', () async { iosEnvironment.defines.remove(kTargetPlatform); - expect(const NativeAssets().build(iosEnvironment), throwsA(isA())); + expect(const DartBuildForNative().build(iosEnvironment), throwsA(isA())); }); testUsingContext('NativeAssets defaults to ios archs if missing', () async { @@ -77,14 +77,12 @@ void main() { iosEnvironment.defines.remove(kIosArchs); final FlutterNativeAssetsBuildRunner buildRunner = FakeFlutterNativeAssetsBuildRunner(); - await NativeAssets(buildRunner: buildRunner).build(iosEnvironment); + await DartBuildForNative(buildRunner: buildRunner).build(iosEnvironment); + await const InstallCodeAssets().build(iosEnvironment); - final File nativeAssetsYaml = - iosEnvironment.buildDir.childFile('native_assets.yaml'); - - final File depsFile = iosEnvironment.buildDir.childFile('native_assets.d'); - expect(depsFile, exists); - expect(nativeAssetsYaml, exists); + expect(iosEnvironment.buildDir.childFile(DartBuild.depFilename), exists); + expect(iosEnvironment.buildDir.childFile(InstallCodeAssets.depFilename), exists); + expect(iosEnvironment.buildDir.childFile(InstallCodeAssets.nativeAssetsFilename), exists); }); testUsingContext('NativeAssets throws error if missing sdk root', overrides: { @@ -98,7 +96,7 @@ void main() { ]); iosEnvironment.defines.remove(kSdkRoot); - expect(NativeAssets(buildRunner: buildRunner).build(iosEnvironment), throwsA(isA())); + expect(DartBuildForNative(buildRunner: buildRunner).build(iosEnvironment), throwsA(isA())); }); // The NativeAssets Target should _always_ be creating a yaml an d file. @@ -118,10 +116,12 @@ void main() { await createPackageConfig(iosEnvironment); final FlutterNativeAssetsBuildRunner buildRunner = FakeFlutterNativeAssetsBuildRunner(); - await NativeAssets(buildRunner: buildRunner).build(iosEnvironment); + await DartBuildForNative(buildRunner: buildRunner).build(iosEnvironment); + await const InstallCodeAssets().build(iosEnvironment); - expect(iosEnvironment.buildDir.childFile('native_assets.d'), exists); - expect(iosEnvironment.buildDir.childFile('native_assets.yaml'), exists); + expect(iosEnvironment.buildDir.childFile(DartBuild.depFilename), exists); + expect(iosEnvironment.buildDir.childFile(InstallCodeAssets.depFilename), exists); + expect(iosEnvironment.buildDir.childFile(InstallCodeAssets.nativeAssetsFilename), exists); }, ); } @@ -212,20 +212,34 @@ void main() { codeAssets: codeAssets, ), ); - await NativeAssets(buildRunner: buildRunner).build(iosEnvironment); + await DartBuildForNative(buildRunner: buildRunner).build(iosEnvironment); + await const InstallCodeAssets().build(iosEnvironment); - final File nativeAssetsYaml = iosEnvironment.buildDir.childFile('native_assets.yaml'); - final File depsFile = iosEnvironment.buildDir.childFile('native_assets.d'); - expect(depsFile, exists); - // We don't care about the specific format, but it should contain the - // yaml as the file depending on the source files that went in to the - // build. + // We don't care about the specific format, but + // * dart build output should depend on C source + // * installation output should depend on shared library from dart build + + final File dartBuildResult = iosEnvironment.buildDir.childFile(DartBuild.dartBuildResultFilename); + final File buildDepsFile = iosEnvironment.buildDir.childFile(DartBuild.depFilename); + expect(buildDepsFile, exists); expect( - depsFile.readAsStringSync(), + buildDepsFile.readAsStringSync(), + stringContainsInOrder([ + dartBuildResult.path, + ':', + 'src/foo.c', + ]), + ); + + final File nativeAssetsYaml = iosEnvironment.buildDir.childFile(InstallCodeAssets.nativeAssetsFilename); + final File installDepsFile = iosEnvironment.buildDir.childFile(InstallCodeAssets.depFilename); + expect(installDepsFile, exists); + expect( + installDepsFile.readAsStringSync(), stringContainsInOrder([ nativeAssetsYaml.path, ':', - 'src/foo.c', + 'foo.framework/foo', ]), ); expect(nativeAssetsYaml, exists); @@ -281,7 +295,7 @@ void main() { codeAssets: codeAssets, ), ); - await NativeAssets(buildRunner: buildRunner).build(androidEnvironment); + await DartBuildForNative(buildRunner: buildRunner).build(androidEnvironment); expect( buildRunner.lastBuildMode, native_assets_cli.BuildMode.release, diff --git a/packages/flutter_tools/test/general.shard/isolated/ios/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/ios/native_assets_test.dart index 705210cdbe9..141703026e2 100644 --- a/packages/flutter_tools/test/general.shard/isolated/ios/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/ios/native_assets_test.dart @@ -11,6 +11,7 @@ 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/build_system/build_system.dart'; +import 'package:flutter_tools/src/build_system/targets/native_assets.dart'; import 'package:flutter_tools/src/features.dart'; import 'package:flutter_tools/src/globals.dart' as globals; import 'package:flutter_tools/src/isolated/native_assets/native_assets.dart'; @@ -159,7 +160,7 @@ void main() { } final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); - final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.yaml').uri; + final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile(InstallCodeAssets.nativeAssetsFilename).uri; await packageConfig.parent.create(); await packageConfig.create(); @@ -192,18 +193,26 @@ void main() { ? null : FakeFlutterNativeAssetsBuilderResult.fromAssets(codeAssets: codeAssets(config.targetOS, config.codeConfig)), ); - await runFlutterSpecificDartBuild( - environmentDefines: { - kBuildMode: buildMode.cliName, - kSdkRoot: '.../iPhone Simulator', - kIosArchs: 'arm64 x86_64', - }, + final Map environmentDefines = { + kBuildMode: buildMode.cliName, + kSdkRoot: '.../iPhone Simulator', + kIosArchs: 'arm64 x86_64', + }; + final DartBuildResult dartBuildResult = await runFlutterSpecificDartBuild( + environmentDefines: environmentDefines, targetPlatform: TargetPlatform.ios, projectUri: projectUri, - nativeAssetsYamlUri: nonFlutterTesterAssetUri, fileSystem: fileSystem, buildRunner: buildRunner, ); + await installCodeAssets( + dartBuildResult: dartBuildResult, + environmentDefines: environmentDefines, + targetPlatform: TargetPlatform.ios, + projectUri: projectUri, + fileSystem: fileSystem, + nativeAssetsFileUri: nonFlutterTesterAssetUri, + ); expect( (globals.logger as BufferLogger).traceText, stringContainsInOrder([ @@ -211,10 +220,7 @@ void main() { 'Building native assets for [ios_arm64, ios_x64] $buildMode done.', ]), ); - expect( - environment.buildDir.childFile('native_assets.yaml'), - exists, - ); + expect(environment.buildDir.childFile(InstallCodeAssets.nativeAssetsFilename), exists); // Two archs. expect(buildRunner.buildInvocations, 2); expect( diff --git a/packages/flutter_tools/test/general.shard/isolated/linux/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/linux/native_assets_test.dart index 74bf755fc49..1b76981a228 100644 --- a/packages/flutter_tools/test/general.shard/isolated/linux/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/linux/native_assets_test.dart @@ -53,7 +53,6 @@ void main() { ProcessManager: () => FakeProcessManager.empty(), }, () async { final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); - final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.yaml').uri; await packageConfig.create(recursive: true); await runFlutterSpecificDartBuild( @@ -62,7 +61,6 @@ void main() { }, targetPlatform: TargetPlatform.linux_x64, projectUri: projectUri, - nativeAssetsYamlUri: nonFlutterTesterAssetUri, fileSystem: fileSystem, buildRunner: _BuildRunnerWithoutClang(), ); diff --git a/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_test.dart index 524cb733ecc..c674cca87e2 100644 --- a/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_test.dart @@ -10,6 +10,7 @@ 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/build_system/build_system.dart'; +import 'package:flutter_tools/src/build_system/targets/native_assets.dart'; import 'package:flutter_tools/src/dart/package_map.dart'; import 'package:flutter_tools/src/features.dart'; import 'package:flutter_tools/src/globals.dart' as globals; @@ -265,7 +266,7 @@ void main() { return; } final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); - final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.yaml').uri; + final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile(InstallCodeAssets.nativeAssetsFilename).uri; await packageConfig.parent.create(); await packageConfig.create(); @@ -297,17 +298,30 @@ void main() { ? null : FakeFlutterNativeAssetsBuilderResult.fromAssets(codeAssets: codeAssets(config.targetOS, config.codeConfig)), ); - final (_, Uri nativeAssetsYaml) = await runFlutterSpecificDartBuild( - environmentDefines: { - kBuildMode: buildMode.cliName, - kDarwinArchs: 'arm64 x86_64', - }, - targetPlatform: flutterTester ? TargetPlatform.tester : TargetPlatform.darwin, + final Map environmentDefines = { + kBuildMode: buildMode.cliName, + kDarwinArchs: 'arm64 x86_64', + }; + final TargetPlatform targetPlatform = flutterTester ? TargetPlatform.tester : TargetPlatform.darwin; + final DartBuildResult dartBuildResult = await runFlutterSpecificDartBuild( + environmentDefines: environmentDefines, + targetPlatform: targetPlatform, projectUri: projectUri, - nativeAssetsYamlUri: flutterTester ? null : nonFlutterTesterAssetUri, fileSystem: fileSystem, buildRunner: buildRunner, ); + final Uri nativeAssetsFileUri = flutterTester + ? projectUri.resolve('build/native_assets/macos/${InstallCodeAssets.nativeAssetsFilename}') + : nonFlutterTesterAssetUri; + + await installCodeAssets( + dartBuildResult: dartBuildResult, + environmentDefines: environmentDefines, + targetPlatform: targetPlatform, + projectUri: projectUri, + fileSystem: fileSystem, + nativeAssetsFileUri: nativeAssetsFileUri , + ); final String expectedArchsBeingBuilt = flutterTester ? (isArm64 ? 'macos_arm64' : 'macos_x64') : '[macos_arm64, macos_x64]'; @@ -318,14 +332,9 @@ void main() { 'Building native assets for $expectedArchsBeingBuilt $buildMode done.', ]), ); + final String nativeAssetsFileContent = await fileSystem.file(nativeAssetsFileUri).readAsString(); expect( - nativeAssetsYaml, - flutterTester - ? projectUri.resolve('build/native_assets/macos/native_assets.yaml') - : nonFlutterTesterAssetUri - ); - expect( - await fileSystem.file(nativeAssetsYaml).readAsString(), + nativeAssetsFileContent , stringContainsInOrder([ 'package:bar/bar.dart', if (flutterTester) @@ -337,7 +346,7 @@ void main() { ]), ); expect( - await fileSystem.file(nativeAssetsYaml).readAsString(), + nativeAssetsFileContent, stringContainsInOrder([ 'package:buz/buz.dart', if (flutterTester) diff --git a/packages/flutter_tools/test/general.shard/isolated/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/native_assets_test.dart index dce1d3187f4..64b3957617d 100644 --- a/packages/flutter_tools/test/general.shard/isolated/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/native_assets_test.dart @@ -10,6 +10,7 @@ import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/build_system/build_system.dart'; +import 'package:flutter_tools/src/build_system/targets/native_assets.dart'; import 'package:flutter_tools/src/features.dart'; import 'package:flutter_tools/src/globals.dart' as globals; import 'package:flutter_tools/src/isolated/native_assets/native_assets.dart'; @@ -69,14 +70,12 @@ void main() { testUsingContext('build with no package config', overrides: { ProcessManager: () => FakeProcessManager.empty(), }, () async { - final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.yaml').uri; await runFlutterSpecificDartBuild( environmentDefines: { kBuildMode: BuildMode.debug.cliName, }, targetPlatform: TargetPlatform.windows_x64, projectUri: projectUri, - nativeAssetsYamlUri: nonFlutterTesterAssetUri, fileSystem: fileSystem, buildRunner: FakeFlutterNativeAssetsBuildRunner( hasPackageConfigResult: false, @@ -171,7 +170,7 @@ void main() { ); expect( nativeAssetsYaml, - projectUri.resolve('build/native_assets/windows/native_assets.yaml'), + projectUri.resolve('build/native_assets/windows/${InstallCodeAssets.nativeAssetsFilename}'), ); expect( await fileSystem.file(nativeAssetsYaml).readAsString(), @@ -203,19 +202,18 @@ void main() { file: file, ); + final Map environmentDefines = { + kBuildMode: BuildMode.release.cliName, + }; final List codeAssets = [ makeCodeAsset('malloc', LookupInProcess()), makeCodeAsset('free', LookupInExecutable()), makeCodeAsset('draw', DynamicLoadingSystem(Uri.file('/usr/lib/skia.so'))), ]; - - await runFlutterSpecificDartBuild( - environmentDefines: { - kBuildMode: BuildMode.release.cliName, - }, + final DartBuildResult dartBuildResult = await runFlutterSpecificDartBuild( + environmentDefines: environmentDefines, targetPlatform: TargetPlatform.linux_x64, projectUri: projectUri, - nativeAssetsYamlUri: nonFlutterTesterAssetUri, fileSystem: fileSystem, buildRunner: FakeFlutterNativeAssetsBuildRunner( packagesWithNativeAssetsResult: [ @@ -225,6 +223,14 @@ void main() { linkResult: FakeFlutterNativeAssetsBuilderResult.fromAssets(codeAssets: codeAssets), ), ); + await installCodeAssets( + dartBuildResult: dartBuildResult, + environmentDefines: environmentDefines, + targetPlatform: TargetPlatform.windows_x64, + projectUri: projectUri, + fileSystem: fileSystem, + nativeAssetsFileUri: nonFlutterTesterAssetUri, + ); expect(testLogger.traceText, isNot(contains('Copying native assets to'))); }); @@ -232,7 +238,6 @@ void main() { ProcessManager: () => FakeProcessManager.empty(), }, () async { final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); - final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.yaml').uri; await packageConfig.parent.create(); await packageConfig.create(); expect( @@ -242,7 +247,6 @@ void main() { }, targetPlatform: TargetPlatform.windows_x64, projectUri: projectUri, - nativeAssetsYamlUri: nonFlutterTesterAssetUri, fileSystem: fileSystem, buildRunner: FakeFlutterNativeAssetsBuildRunner( packagesWithNativeAssetsResult: [ @@ -262,16 +266,17 @@ void main() { ProcessManager: () => FakeProcessManager.empty(), }, () async { final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); - final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.yaml').uri; + final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile(InstallCodeAssets.nativeAssetsFilename).uri; await packageConfig.parent.create(); await packageConfig.create(); - final (_, Uri nativeAssetsYaml) = await runFlutterSpecificDartBuild( - environmentDefines: { - kBuildMode: BuildMode.debug.cliName, - }, + + final Map environmentDefines = { + kBuildMode: BuildMode.debug.cliName, + }; + final DartBuildResult dartBuildResult = await runFlutterSpecificDartBuild( + environmentDefines: environmentDefines, targetPlatform: TargetPlatform.windows_x64, projectUri: projectUri, - nativeAssetsYamlUri: nonFlutterTesterAssetUri, fileSystem: fileSystem, buildRunner: FakeFlutterNativeAssetsBuildRunner( packagesWithNativeAssetsResult: [ @@ -279,9 +284,16 @@ void main() { ], ), ); - expect(nativeAssetsYaml, nonFlutterTesterAssetUri); + await installCodeAssets( + dartBuildResult: dartBuildResult, + environmentDefines: environmentDefines, + targetPlatform: TargetPlatform.windows_x64, + projectUri: projectUri, + fileSystem: fileSystem, + nativeAssetsFileUri: nonFlutterTesterAssetUri, + ); expect( - await fileSystem.file(nativeAssetsYaml).readAsString(), + await fileSystem.file(nonFlutterTesterAssetUri).readAsString(), isNot(contains('package:bar/bar.dart')), ); expect( @@ -323,7 +335,6 @@ void main() { }, () async { final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); - final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.yaml').uri; await packageConfig.parent.create(); await packageConfig.create(); expect( @@ -333,7 +344,6 @@ void main() { }, targetPlatform: TargetPlatform.linux_x64, projectUri: projectUri, - nativeAssetsYamlUri: nonFlutterTesterAssetUri, fileSystem: fileSystem, buildRunner: FakeFlutterNativeAssetsBuildRunner( packagesWithNativeAssetsResult: [ @@ -355,7 +365,6 @@ void main() { }, () async { final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); - final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.yaml').uri; await packageConfig.parent.create(); await packageConfig.create(); @@ -376,14 +385,13 @@ void main() { file: file, ); - final (DartBuildResult result, _) = await runFlutterSpecificDartBuild( + final DartBuildResult result = await runFlutterSpecificDartBuild( environmentDefines: { // Release mode means the dart build has linking enabled. kBuildMode: BuildMode.release.cliName, }, targetPlatform: TargetPlatform.linux_x64, projectUri: projectUri, - nativeAssetsYamlUri: nonFlutterTesterAssetUri, fileSystem: fileSystem, buildRunner: FakeFlutterNativeAssetsBuildRunner( packagesWithNativeAssetsResult: [ diff --git a/packages/flutter_tools/test/general.shard/isolated/windows/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/windows/native_assets_test.dart index ad0658a1ee3..c05c308a6a9 100644 --- a/packages/flutter_tools/test/general.shard/isolated/windows/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/windows/native_assets_test.dart @@ -10,6 +10,7 @@ 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/build_system/build_system.dart'; +import 'package:flutter_tools/src/build_system/targets/native_assets.dart'; import 'package:flutter_tools/src/dart/package_map.dart'; import 'package:flutter_tools/src/features.dart'; import 'package:flutter_tools/src/globals.dart' as globals; @@ -71,7 +72,7 @@ void main() { ProcessManager: () => FakeProcessManager.empty(), }, () async { final File packageConfig = environment.projectDir.childDirectory('.dart_tool').childFile('package_config.json'); - final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.yaml').uri; + final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile(InstallCodeAssets.nativeAssetsFilename).uri; await packageConfig.parent.create(); await packageConfig.create(); final File dylibAfterCompiling = fileSystem.file('bar.dll'); @@ -98,18 +99,33 @@ void main() { : FakeFlutterNativeAssetsBuilderResult.fromAssets(codeAssets: codeAssets, ), ); - final (_, Uri nativeAssetsYaml) = await runFlutterSpecificDartBuild( - environmentDefines: { - kBuildMode: buildMode.cliName, - }, - targetPlatform: flutterTester - ? TargetPlatform.tester - : TargetPlatform.windows_x64, + final Map environmentDefines = { + kBuildMode: buildMode.cliName, + }; + final TargetPlatform targetPlatform = flutterTester + ? TargetPlatform.tester + : TargetPlatform.windows_x64; + final DartBuildResult dartBuildResult = await runFlutterSpecificDartBuild( + environmentDefines: environmentDefines, + targetPlatform: targetPlatform, projectUri: projectUri, - nativeAssetsYamlUri: flutterTester ? null : nonFlutterTesterAssetUri, fileSystem: fileSystem, buildRunner: buildRunner, ); + final String expectedDirectory = flutterTester + ? native_assets_cli.OS.current.toString() + : 'windows'; + final Uri nativeAssetsFileUri = flutterTester + ? projectUri.resolve('build/native_assets/$expectedDirectory/${InstallCodeAssets.nativeAssetsFilename}') + : nonFlutterTesterAssetUri; + await installCodeAssets( + dartBuildResult: dartBuildResult, + environmentDefines: environmentDefines, + targetPlatform: targetPlatform, + projectUri: projectUri, + fileSystem: fileSystem, + nativeAssetsFileUri: nativeAssetsFileUri, + ); final String expectedOS = flutterTester ? native_assets_cli.Target.current.toString() : 'windows_x64'; @@ -120,16 +136,8 @@ void main() { 'Building native assets for $expectedOS $buildMode done.', ]), ); - final String expectedDirectory = flutterTester - ? native_assets_cli.OS.current.toString() - : 'windows'; - expect(nativeAssetsYaml, - flutterTester - ? projectUri.resolve('build/native_assets/$expectedDirectory/native_assets.yaml') - : nonFlutterTesterAssetUri - ); expect( - await fileSystem.file(nativeAssetsYaml).readAsString(), + await fileSystem.file(nativeAssetsFileUri).readAsString(), stringContainsInOrder([ 'package:bar/bar.dart', if (flutterTester) From 917b48d942cdb770270a3efc6634af9e7fb4039d Mon Sep 17 00:00:00 2001 From: Yegor Date: Fri, 15 Nov 2024 14:13:31 -0800 Subject: [PATCH 093/386] Style change in Flutter-Web-Triage.md (#159006) Mostly just testing the MQ functionality --- docs/triage/Flutter-Web-Triage.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/triage/Flutter-Web-Triage.md b/docs/triage/Flutter-Web-Triage.md index 830bcacf5a9..7f76a055657 100644 --- a/docs/triage/Flutter-Web-Triage.md +++ b/docs/triage/Flutter-Web-Triage.md @@ -1,9 +1,9 @@ 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): +* 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) @@ -11,7 +11,7 @@ When triaging web issues follow the following process: - [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+) +* 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+) From 4d3bbf30c8a8d0ec9acc25228728019e515ac9d7 Mon Sep 17 00:00:00 2001 From: Greg Spencer Date: Fri, 15 Nov 2024 14:39:41 -0800 Subject: [PATCH 094/386] Make the focus node on SelectableRegion optional. (#158994) ## Description This makes the `focusNode` for `SelectableRegion` optional so that: - Users of the widget are no longer required to use `SelectableRegion` from within a `StatefulWidget` - They aren't likely to forget to dispose of a node they didn't supply. - Simpler to use, and the node is not used very often anyhow. Also made the `SelectableRegion` sample actually use `SelectableRegion`. ## Tests - Modified all the `SelectableRegion` tests to remove 3 identical lines of boilerplate from each (except 2, which actually used their focus nodes). --- .../selectable_region.0.dart | 3 +- .../lib/src/material/selection_area.dart | 10 +- .../lib/src/widgets/selectable_region.dart | 39 ++- .../test/widgets/default_colors_test.dart | 3 - .../test/widgets/selectable_region_test.dart | 286 ------------------ 5 files changed, 28 insertions(+), 313 deletions(-) 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..869d5a01950 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( diff --git a/packages/flutter/lib/src/material/selection_area.dart b/packages/flutter/lib/src/material/selection_area.dart index 5d305589c57..be1a26aa2e5 100644 --- a/packages/flutter/lib/src/material/selection_area.dart +++ b/packages/flutter/lib/src/material/selection_area.dart @@ -109,18 +109,10 @@ 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(); - } - @override Widget build(BuildContext context) { assert(debugCheckHasMaterialLocalizations(context)); @@ -133,7 +125,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/widgets/selectable_region.dart b/packages/flutter/lib/src/widgets/selectable_region.dart index 002237cdc59..dace673d580 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( @@ -218,7 +216,7 @@ class SelectableRegion extends StatefulWidget { const SelectableRegion({ super.key, this.contextMenuBuilder, - required this.focusNode, + this.focusNode, required this.selectionControls, required this.child, this.magnifierConfiguration = TextMagnifierConfiguration.disabled, @@ -235,7 +233,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 +371,14 @@ 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')); + @override void initState() { super.initState(); - widget.focusNode.addListener(_handleFocusChanged); + _focusNode.addListener(_handleFocusChanged); _initMouseGestureRecognizer(); _initTouchGestureRecognizer(); // Right clicks. @@ -426,9 +428,15 @@ class SelectableRegionState extends State with TextSelectionDe 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 +447,7 @@ class SelectableRegionState extends State with TextSelectionDe } void _handleFocusChanged() { - if (!widget.focusNode.hasFocus) { + if (!_focusNode.hasFocus) { if (kIsWeb) { PlatformSelectableRegionContextMenu.detach(_selectionDelegate); } @@ -628,7 +636,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: @@ -843,7 +851,7 @@ class SelectableRegionState extends State with TextSelectionDe void _handleTouchLongPressStart(LongPressStartDetails details) { HapticFeedback.selectionClick(); - widget.focusNode.requestFocus(); + _focusNode.requestFocus(); _selectWordAt(offset: details.globalPosition); // Platforms besides Android will show the text selection handles when // the long press is initiated. Android shows the text selection handles when @@ -883,7 +891,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: @@ -1706,6 +1714,9 @@ class SelectableRegionState extends State with TextSelectionDe _selectionOverlay?.hideMagnifier(); _selectionOverlay?.dispose(); _selectionOverlay = null; + widget.focusNode?.removeListener(_handleFocusChanged); + _localFocusNode?.removeListener(_handleFocusChanged); + _localFocusNode?.dispose(); super.dispose(); } @@ -1730,9 +1741,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, ), ), 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/selectable_region_test.dart b/packages/flutter/test/widgets/selectable_region_test.dart index bb8a0ac483a..c20112d78bc 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), ), @@ -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), ), @@ -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'), @@ -1531,13 +1432,9 @@ void main() { }, variant: TargetPlatformVariant.mobile()); testWidgets('mouse can select word-by-word 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 Center( child: Text('How are you'), @@ -1604,13 +1501,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 +1546,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 +1603,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 +1653,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 +1724,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 +1776,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 +1838,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 +1910,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 +1959,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 +1998,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 +2057,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 +2087,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 +2129,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 +2169,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 +2215,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 +2304,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 +2377,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 +2458,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 +2530,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 +2634,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 +2754,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 +2878,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 +3060,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 +3099,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 +3144,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 +3192,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 +3242,6 @@ void main() { await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Scaffold( body: Center( @@ -3478,13 +3282,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 +3325,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 +3369,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 +3409,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 +3446,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 +3487,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 +3519,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 +3526,6 @@ void main() { children: [ const Text('How are you?'), SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text('Good, and you?'), ), @@ -3773,8 +3556,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 +3563,6 @@ void main() { children: [ const Text('How are you?'), SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text('Good, and you?'), ), @@ -3811,13 +3591,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 +3633,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 +3670,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 +3707,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 +3743,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 +3783,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 +3843,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 +3955,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 +4046,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 +4126,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 +4227,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 +4240,6 @@ void main() { return fakeMagnifier; }, ), - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text(text), ), @@ -4544,13 +4291,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 +4356,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 +4409,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 +4473,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 +4530,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 +4587,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: [ @@ -4919,13 +4648,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, @@ -4968,14 +4694,11 @@ void main() { 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 +4832,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 +4988,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 +5022,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( From ec2ab541dd71e8ee800b190671b476b80311edb6 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Fri, 15 Nov 2024 14:54:06 -0800 Subject: [PATCH 095/386] Switch `flutter_build_apk_health_tests` to use a subset of current tests. (#159004) Towards https://github.com/flutter/flutter/issues/159000 as part of debugging issues such as https://github.com/flutter/flutter/issues/158560. On a `bringup: true` shard, run a number of `flutter build apk` tests in succession to try and routinely trigger timeouts and crashes, so we can test other hypotheses on how to fix this problem (i.e. potentially around increasing memory, changing daemon configuration, aggressively killing processes, etc). --- dev/bots/test.dart | 11 ++- dev/bots/utils.dart | 6 ++ .../test/flutter_build_apk.shard/README.md | 3 - .../flutter_build_apk_test.dart | 87 ------------------- .../android_e2e_api_test.dart | 4 + ...d_gradle_deprecated_plugin_apply_test.dart | 4 + ...tter_plugins_strings_in_comments_test.dart | 4 + ...roid_gradle_print_build_variants_test.dart | 4 + ...android_plugin_example_app_build_test.dart | 4 + ...ter_build_with_compilation_error_test.dart | 4 + .../native_assets_agp_version_test.dart | 2 + .../isolated/native_assets_test.dart | 3 + ...e_assets_without_cbuild_assemble_test.dart | 5 ++ 13 files changed, 45 insertions(+), 96 deletions(-) delete mode 100644 packages/flutter_tools/test/flutter_build_apk.shard/README.md delete mode 100644 packages/flutter_tools/test/flutter_build_apk.shard/flutter_build_apk_test.dart diff --git a/dev/bots/test.dart b/dev/bots/test.dart index 7073a9f3b03..0c9ff764d29 100644 --- a/dev/bots/test.dart +++ b/dev/bots/test.dart @@ -236,16 +236,15 @@ Future _runIntegrationToolTests() async { } Future _runFlutterBuildApkHealthTests() async { - final List allTests = Directory(path.join(_toolsPath, 'test', 'flutter_build_apk.shard')) - .listSync(recursive: true).whereType() - .map((FileSystemEntity entry) => path.relative(entry.path, from: _toolsPath)) - .where((String testPath) => path.basename(testPath).endsWith('_test.dart')).toList(); - await runDartTest( _toolsPath, forceSingleCore: true, - testPaths: selectIndexOfTotalSubshard(allTests), + testPaths: [ + path.join(_toolsPath, 'test', 'integration.shard'), + ], collectMetrics: true, + runSkipped: true, + tags: ['flutter-build-apk'], ); } diff --git a/dev/bots/utils.dart b/dev/bots/utils.dart index be8ab9b028d..3ed0958ff02 100644 --- a/dev/bots/utils.dart +++ b/dev/bots/utils.dart @@ -342,6 +342,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 +381,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, diff --git a/packages/flutter_tools/test/flutter_build_apk.shard/README.md b/packages/flutter_tools/test/flutter_build_apk.shard/README.md deleted file mode 100644 index d5d85c11f4b..00000000000 --- a/packages/flutter_tools/test/flutter_build_apk.shard/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `flutter_build_apk.shard` - -Integration tests that debug why `flutter build apk` sometimes stalls on CI. diff --git a/packages/flutter_tools/test/flutter_build_apk.shard/flutter_build_apk_test.dart b/packages/flutter_tools/test/flutter_build_apk.shard/flutter_build_apk_test.dart deleted file mode 100644 index 8a72d191c7f..00000000000 --- a/packages/flutter_tools/test/flutter_build_apk.shard/flutter_build_apk_test.dart +++ /dev/null @@ -1,87 +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 'dart:io' as io; - -import 'package:file/file.dart'; - -import '../integration.shard/test_utils.dart'; -import '../src/common.dart'; - -void main() { - final String flutterRoot = getFlutterRoot(); - final String flutterBin = fileSystem.path.join(flutterRoot, 'bin', 'flutter'); - - late Directory tmpDir; - - setUp(() { - tmpDir = fileSystem.systemTempDirectory.createTempSync(); - }); - - tearDown(() { - tryToDelete(tmpDir); - }); - - Future setGradleLoggingLevel( - String level, { - required Directory projectDir, - }) async { - // Open gradle.properties and append to it. - final Directory androidDir = projectDir.childDirectory('android'); - final File gradleDotProperties = androidDir.childFile('gradle.properties'); - final io.IOSink sink = gradleDotProperties.openWrite(mode: FileMode.append); - - sink.writeln('org.gradle.logging.level=$level'); - await sink.flush(); - await sink.close(); - - // For debugging, print the current output. - io.stderr.writeln('${gradleDotProperties.path}:'); - io.stderr.writeln(gradleDotProperties.readAsStringSync()); - } - - // Normally these tests should take about a minute, but sometimes for - // unknown reasons they can take 30m+ and timeout. The intent behind this loop - // is to get more information on what exactly is happening. - for (int i = 1; i <= 10; i++) { - test('flutter build apk | attempt $i of 10', () async { - final String package = 'flutter_build_apk_test_$i'; - - // Create a new Flutter app. - await expectLater( - processManager.run( - [ - flutterBin, - 'create', - package, - ], - workingDirectory: tmpDir.path, - ), - completion(const ProcessResultMatcher()), - reason: 'Should create a new blank Flutter project', - ); - - // Tweak verbosity of just gradle. - final Directory projectDir = tmpDir.childDirectory(package); - await setGradleLoggingLevel('debug', projectDir: projectDir); - - // Build the APK. - final List args = [ - flutterBin, - '--verbose', - 'build', - 'apk', - '--debug', - ]; - io.stderr.writeln('Running $args...'); - - final io.Process process = await processManager.start( - args, - workingDirectory: projectDir.path, - mode: io.ProcessStartMode.inheritStdio, - ); - await expectLater(process.exitCode, completion(0)); - }); - } -} diff --git a/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart b/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart index 73d11c688b1..9c1c677f6a7 100644 --- a/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// TODO(matanlurey): Remove after debugging https://github.com/flutter/flutter/issues/159000. +@Tags(['flutter-build-apk']) +library; + import 'package:file/file.dart'; import 'package:flutter_tools/src/base/io.dart'; diff --git a/packages/flutter_tools/test/integration.shard/android_gradle_deprecated_plugin_apply_test.dart b/packages/flutter_tools/test/integration.shard/android_gradle_deprecated_plugin_apply_test.dart index 5964218eed6..91bc50622af 100644 --- a/packages/flutter_tools/test/integration.shard/android_gradle_deprecated_plugin_apply_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_gradle_deprecated_plugin_apply_test.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// TODO(matanlurey): Remove after debugging https://github.com/flutter/flutter/issues/159000. +@Tags(['flutter-build-apk']) +library; + import 'dart:convert'; import 'package:file/file.dart'; diff --git a/packages/flutter_tools/test/integration.shard/android_gradle_legacy_flutter_plugins_strings_in_comments_test.dart b/packages/flutter_tools/test/integration.shard/android_gradle_legacy_flutter_plugins_strings_in_comments_test.dart index d5d7a46d7c9..041b3aa4538 100644 --- a/packages/flutter_tools/test/integration.shard/android_gradle_legacy_flutter_plugins_strings_in_comments_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_gradle_legacy_flutter_plugins_strings_in_comments_test.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// TODO(matanlurey): Remove after debugging https://github.com/flutter/flutter/issues/159000. +@Tags(['flutter-build-apk']) +library; + // This test can be removed once https://github.com/flutter/flutter/issues/155484 is resolved. import 'package:flutter_tools/src/base/file_system.dart'; diff --git a/packages/flutter_tools/test/integration.shard/android_gradle_print_build_variants_test.dart b/packages/flutter_tools/test/integration.shard/android_gradle_print_build_variants_test.dart index 085d3a58328..fa2c72359fe 100644 --- a/packages/flutter_tools/test/integration.shard/android_gradle_print_build_variants_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_gradle_print_build_variants_test.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// TODO(matanlurey): Remove after debugging https://github.com/flutter/flutter/issues/159000. +@Tags(['flutter-build-apk']) +library; + import 'dart:convert'; import 'package:collection/collection.dart'; diff --git a/packages/flutter_tools/test/integration.shard/android_plugin_example_app_build_test.dart b/packages/flutter_tools/test/integration.shard/android_plugin_example_app_build_test.dart index 755ef2df449..8bb28785faf 100644 --- a/packages/flutter_tools/test/integration.shard/android_plugin_example_app_build_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_plugin_example_app_build_test.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// TODO(matanlurey): Remove after debugging https://github.com/flutter/flutter/issues/159000. +@Tags(['flutter-build-apk']) +library; + import 'package:file_testing/file_testing.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/io.dart'; diff --git a/packages/flutter_tools/test/integration.shard/flutter_build_with_compilation_error_test.dart b/packages/flutter_tools/test/integration.shard/flutter_build_with_compilation_error_test.dart index 07de04c3c1c..c37ec4f66cf 100644 --- a/packages/flutter_tools/test/integration.shard/flutter_build_with_compilation_error_test.dart +++ b/packages/flutter_tools/test/integration.shard/flutter_build_with_compilation_error_test.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// TODO(matanlurey): Remove after debugging https://github.com/flutter/flutter/issues/159000. +@Tags(['flutter-build-apk']) +library; + import 'package:file/file.dart'; import 'package:flutter_tools/src/base/io.dart'; diff --git a/packages/flutter_tools/test/integration.shard/isolated/native_assets_agp_version_test.dart b/packages/flutter_tools/test/integration.shard/isolated/native_assets_agp_version_test.dart index 25f4e2331e6..41acde68397 100644 --- a/packages/flutter_tools/test/integration.shard/isolated/native_assets_agp_version_test.dart +++ b/packages/flutter_tools/test/integration.shard/isolated/native_assets_agp_version_test.dart @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// TODO(matanlurey): Remove after debugging https://github.com/flutter/flutter/issues/159000. +@Tags(['flutter-build-apk']) @Timeout(Duration(minutes: 10)) library; diff --git a/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart b/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart index c4fe81939a8..572fb2959fb 100644 --- a/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart +++ b/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart @@ -10,6 +10,8 @@ // contain the native assets mapping. // When doing a hot reload, this mapping must stay in place. +// TODO(matanlurey): Remove after debugging https://github.com/flutter/flutter/issues/159000. +@Tags(['flutter-build-apk']) @Timeout(Duration(minutes: 10)) library; @@ -224,6 +226,7 @@ void main() { // TODO(matanlurey): Debug why flutter build apk often timesout. // See https://github.com/flutter/flutter/issues/158560 for details. skip: buildSubcommand == 'apk' ? 'flutter build apk times out' : false, // Temporary workaround for https://github.com/flutter/flutter/issues/158560. + tags: ['flutter-build-apk'], ); } } diff --git a/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart b/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart index f80799d5504..2e36b4f616e 100644 --- a/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart +++ b/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// TODO(matanlurey): Remove after debugging https://github.com/flutter/flutter/issues/159000. +@Tags(['flutter-build-apk']) +library; + import 'dart:io' as io; import 'package:file/file.dart'; @@ -143,6 +147,7 @@ void main(List args) async { // TODO(matanlurey): Debug why flutter build apk often timesout. // See https://github.com/flutter/flutter/issues/158560 for details. skip: buildCommand == 'apk' ? 'flutter build apk times out' : false, // Temporary workaround for https://github.com/flutter/flutter/issues/158560. + tags: ['flutter-build-apk'], ); } From bb5287ad6d5a7b6485f255621a296433e4567a81 Mon Sep 17 00:00:00 2001 From: Yegor Date: Fri, 15 Nov 2024 15:30:59 -0800 Subject: [PATCH 096/386] [flutter triage] Update list of frequent web contributors (#159008) Update list of frequent web contributors --- docs/triage/Flutter-Web-Triage.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/docs/triage/Flutter-Web-Triage.md b/docs/triage/Flutter-Web-Triage.md index 7f76a055657..7e0cfea8e0a 100644 --- a/docs/triage/Flutter-Web-Triage.md +++ b/docs/triage/Flutter-Web-Triage.md @@ -4,13 +4,12 @@ When triaging web issues follow the following process: * 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) + * [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). From ccd581a8deca6c1c33b3b7b75849770c94f70794 Mon Sep 17 00:00:00 2001 From: Flutter GitHub Bot Date: Fri, 15 Nov 2024 19:16:19 -0500 Subject: [PATCH 097/386] Marks Windows windows_desktop_impeller to be unflaky (#158565) The test has been passing for [50 consecutive runs](https://data.corp.google.com/sites/flutter_infra_metrics_datasite/flutter_check_test_flakiness_status_dashboard/?p=BUILDER_NAME:%22Windows%20windows_desktop_impeller%22). This test can be marked as unflaky. --- .ci.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/.ci.yaml b/.ci.yaml index 1fa2ef0546e..c483d1321c2 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -6370,7 +6370,6 @@ targets: - name: Windows windows_desktop_impeller recipe: devicelab/devicelab_drone - bringup: true presubmit: false timeout: 60 properties: From 6281dca4508f1fdfc30c6594fcaa5b3f95b13851 Mon Sep 17 00:00:00 2001 From: Flutter GitHub Bot Date: Fri, 15 Nov 2024 20:48:08 -0500 Subject: [PATCH 098/386] Marks Linux web_benchmarks_skwasm_st to be unflaky (#158563) The test has been passing for [50 consecutive runs](https://data.corp.google.com/sites/flutter_infra_metrics_datasite/flutter_check_test_flakiness_status_dashboard/?p=BUILDER_NAME:%22Linux%20web_benchmarks_skwasm_st%22). This test can be marked as unflaky. Co-authored-by: Jackson Gardner --- .ci.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/.ci.yaml b/.ci.yaml index c483d1321c2..df589f42a29 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -1561,7 +1561,6 @@ targets: - name: Linux web_benchmarks_skwasm_st recipe: devicelab/devicelab_drone - bringup: true presubmit: false timeout: 60 properties: From 1ef8d512829dad0797ecf5259c508a9f2fa49ad4 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Fri, 15 Nov 2024 21:02:25 -0500 Subject: [PATCH 099/386] Roll Flutter Engine from 619804c0fbb7 to f649330affa8 (47 revisions) (#159015) Roll Flutter Engine from 619804c0fbb7 to f649330affa8 (47 revisions) https://github.com/flutter/engine/compare/619804c0fbb7...f649330affa8 2024-11-16 skia-flutter-autoroll@skia.org Roll Skia from 1ef3b910e064 to 6b0f264bde33 (6 revisions) (flutter/engine#56635) 2024-11-16 zanderso@users.noreply.github.com Revert "Remove `android_jit_release_x86`." (flutter/engine#56634) 2024-11-15 chris@bracken.jp Move SetRenderTargetType to EmbedderTestCompositor (flutter/engine#56626) 2024-11-15 skia-flutter-autoroll@skia.org Roll Dart SDK from b62dadb14d82 to eccb15756020 (2 revisions) (flutter/engine#56630) 2024-11-15 andre.stein.1985@gmail.com [TextInput] Add TextInputType.webSearch (#15762) (flutter/engine#56428) 2024-11-15 mdebbar@google.com [web] Send the correct view ID with semantics actions (flutter/engine#56595) 2024-11-15 41930132+hellohuanlin@users.noreply.github.com [macos] early return to suppress clang-tidy warning (flutter/engine#56588) 2024-11-15 chinmaygarde@google.com [Impeller] libImpeller: Tinker on the README to cross reference the SDK and the example. (flutter/engine#56623) 2024-11-15 chaopeng@google.com [fuchsia] MaybeRunInitialVsyncCallback should only called once (flutter/engine#56429) 2024-11-15 magder@google.com Move mac clangd build from x64 to arm (flutter/engine#56567) 2024-11-15 30870216+gaaclarke@users.noreply.github.com Added assert for opengles thread safety (flutter/engine#56585) 2024-11-15 jonahwilliams@google.com [Impeller] enable OpenGL fallback on Android. (flutter/engine#56591) 2024-11-15 jason-simmons@users.noreply.github.com [Impeller] Maintain separate queues of GLES operations for each thread in the reactor (flutter/engine#56573) 2024-11-15 skia-flutter-autoroll@skia.org Roll Dart SDK from abe86ca4eb01 to b62dadb14d82 (2 revisions) (flutter/engine#56615) 2024-11-15 skia-flutter-autoroll@skia.org Roll Skia from b730eb340852 to 1ef3b910e064 (4 revisions) (flutter/engine#56613) 2024-11-15 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from JkpuAsLzcmYLzf1iX... to UpSQzyXGUhMfedYIh... (flutter/engine#56611) 2024-11-15 skia-flutter-autoroll@skia.org Roll Dart SDK from bf0eeb9d929c to abe86ca4eb01 (1 revision) (flutter/engine#56610) 2024-11-15 skia-flutter-autoroll@skia.org Roll Skia from e5fda8472b21 to b730eb340852 (1 revision) (flutter/engine#56608) 2024-11-15 skia-flutter-autoroll@skia.org Roll Skia from 8ff65da4b8bf to e5fda8472b21 (1 revision) (flutter/engine#56603) 2024-11-15 chris@bracken.jp Move TestMetalContext/Surface to testing namespace (flutter/engine#56602) 2024-11-15 skia-flutter-autoroll@skia.org Roll Dart SDK from 343b9fc6eafe to bf0eeb9d929c (1 revision) (flutter/engine#56604) 2024-11-15 chinmaygarde@google.com [Impeller] Don't enable KHR_debug on Angle. (flutter/engine#56601) 2024-11-15 chinmaygarde@google.com [Impeller] libImpeller: Reset the GL state when transitioning control back to the embedder. (flutter/engine#56597) 2024-11-15 skia-flutter-autoroll@skia.org Roll Skia from 8946ea477b42 to 8ff65da4b8bf (2 revisions) (flutter/engine#56600) 2024-11-14 chinmaygarde@google.com [Impeller] Put test components in the testing namespace. (flutter/engine#56594) 2024-11-14 chinmaygarde@google.com [Impeller] libImpeller: Add a warning about OpenGL state being trampled. (flutter/engine#56599) 2024-11-14 chris@bracken.jp Embedder: Refactor EmbedderConfigBuilder by backend (flutter/engine#56598) 2024-11-14 chris@bracken.jp Migrate Metal translation units to Obj-C++ (flutter/engine#56592) 2024-11-14 skia-flutter-autoroll@skia.org Roll Dart SDK from db4d7d52db48 to 343b9fc6eafe (1 revision) (flutter/engine#56590) 2024-11-14 chris@bracken.jp iOS,macOS: Build/test test_metal_surface_unittests (flutter/engine#56586) 2024-11-14 skia-flutter-autoroll@skia.org Roll Skia from 3222456e63dc to 8946ea477b42 (2 revisions) (flutter/engine#56587) 2024-11-14 skia-flutter-autoroll@skia.org Roll Skia from 16178bf63de7 to 3222456e63dc (3 revisions) (flutter/engine#56584) 2024-11-14 bruno.leroux@gmail.com [Android] Fix Slider semantics double tap behaviors (flutter/engine#56452) 2024-11-14 skia-flutter-autoroll@skia.org Roll Dart SDK from a3b6652100c8 to db4d7d52db48 (1 revision) (flutter/engine#56581) 2024-11-14 chris@bracken.jp Move Vulkan context to EmbedderTestContextVulkan (flutter/engine#56571) 2024-11-14 skia-flutter-autoroll@skia.org Roll Skia from a076435073fc to 16178bf63de7 (1 revision) (flutter/engine#56579) 2024-11-14 skia-flutter-autoroll@skia.org Roll Skia from 70553189e4e8 to a076435073fc (1 revision) (flutter/engine#56577) 2024-11-14 skia-flutter-autoroll@skia.org Roll Skia from fa52f2c1ddba to 70553189e4e8 (1 revision) (flutter/engine#56576) 2024-11-14 skia-flutter-autoroll@skia.org Roll Dart SDK from 3f05b3540cb2 to a3b6652100c8 (3 revisions) (flutter/engine#56575) 2024-11-14 skia-flutter-autoroll@skia.org Roll Skia from ddbd8d1cb8d8 to fa52f2c1ddba (3 revisions) (flutter/engine#56574) 2024-11-14 jonahwilliams@google.com [Android] choose 24 bit depth buffer. (flutter/engine#56553) 2024-11-14 skia-flutter-autoroll@skia.org Roll Skia from 3750b8939c7f to ddbd8d1cb8d8 (1 revision) (flutter/engine#56562) 2024-11-14 robert.ancell@canonical.com Move FlMouseCursorHandler from FlView to FlEngine (flutter/engine#56026) 2024-11-14 jonahwilliams@google.com [Impeller] force software resize usage for GLES backend. (flutter/engine#56511) 2024-11-14 skia-flutter-autoroll@skia.org Roll Dart SDK from 66ab1774bfe9 to 3f05b3540cb2 (2 revisions) (flutter/engine#56564) 2024-11-14 chris@bracken.jp Embedder: Refactor EmbedderTestContext creation (flutter/engine#56563) ... --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 861a8240af8..4fa14f56469 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -619804c0fbb73452a9296e9144c306e6858a43b4 +f649330affa8276b6db18f92341577825777e74a diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index c58a3bfaffb..ab6166afc22 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -JkpuAsLzcmYLzf1iXiGQ0p5YoPanCs_DvglyzbIsKNAC +UpSQzyXGUhMfedYIh48ih8GJ_CBT2cJLH4vlZjnNw-YC From 97f1630305c1ec0dfeef5bdbf33088e805068809 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Fri, 15 Nov 2024 23:18:26 -0500 Subject: [PATCH 100/386] Roll Flutter Engine from f649330affa8 to f23832175b7a (1 revision) (#159016) https://github.com/flutter/engine/compare/f649330affa8...f23832175b7a 2024-11-16 skia-flutter-autoroll@skia.org Roll Dart SDK from eccb15756020 to 77a4ee3266a4 (1 revision) (flutter/engine#56640) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 4fa14f56469..9193e96643a 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -f649330affa8276b6db18f92341577825777e74a +f23832175b7abe18392cb70b3188555538e1b72b From fd276da092dbda4a54ef1cf8743cf2f379b070e7 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sat, 16 Nov 2024 00:05:25 -0500 Subject: [PATCH 101/386] Roll Flutter Engine from f23832175b7a to 98c3b7f8d1a7 (1 revision) (#159017) https://github.com/flutter/engine/compare/f23832175b7a...98c3b7f8d1a7 2024-11-16 chris@bracken.jp Backend-specific EmbedderTestBackingStoreProducers (flutter/engine#56638) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 9193e96643a..eb8188e5cc0 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -f23832175b7abe18392cb70b3188555538e1b72b +98c3b7f8d1a7bc35c5b2d4d557060c997dd2b963 From 4bbaa0dfd167fb35327130ae26af7943dda2dd56 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sat, 16 Nov 2024 02:14:01 -0500 Subject: [PATCH 102/386] Roll Flutter Engine from 98c3b7f8d1a7 to 1800193ba961 (1 revision) (#159019) https://github.com/flutter/engine/compare/98c3b7f8d1a7...1800193ba961 2024-11-16 skia-flutter-autoroll@skia.org Roll Fuchsia Test Scripts from 6FgM4KTbxxmyYoiOs... to OA7UxNZkbxCRfr80A... (flutter/engine#56643) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index eb8188e5cc0..96cb03b49d6 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -98c3b7f8d1a7bc35c5b2d4d557060c997dd2b963 +1800193ba961ee641926a787e6aad762eef88d24 From dc17d943fd86318b9c63e6cc25452798e86db6cd Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sat, 16 Nov 2024 03:38:42 -0500 Subject: [PATCH 103/386] Roll Flutter Engine from 1800193ba961 to 85d445e3cf78 (1 revision) (#159020) https://github.com/flutter/engine/compare/1800193ba961...85d445e3cf78 2024-11-16 skia-flutter-autoroll@skia.org Roll Dart SDK from 77a4ee3266a4 to d47c22e5f63a (1 revision) (flutter/engine#56644) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 96cb03b49d6..d1399e8e948 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -1800193ba961ee641926a787e6aad762eef88d24 +85d445e3cf78147f30398eeda1c053942991bbaf From 7bd353dcceaa9bb673a0973982bd4dfa45563f1c Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sat, 16 Nov 2024 14:50:38 -0500 Subject: [PATCH 104/386] Roll Flutter Engine from 85d445e3cf78 to 908061196148 (3 revisions) (#159032) https://github.com/flutter/engine/compare/85d445e3cf78...908061196148 2024-11-16 41930132+hellohuanlin@users.noreply.github.com [ios]fix unused variable clang tidy warning (flutter/engine#56637) 2024-11-16 skia-flutter-autoroll@skia.org Roll Skia from 6b0f264bde33 to f8ec97344733 (1 revision) (flutter/engine#56646) 2024-11-16 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from UpSQzyXGUhMfedYIh... to c5padahsa9sMecBb3... (flutter/engine#56645) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from UpSQzyXGUhMf to c5padahsa9sM If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index d1399e8e948..058642ae4e4 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -85d445e3cf78147f30398eeda1c053942991bbaf +9080611961485256a1eead107ace976cbcd2f070 diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index ab6166afc22..ff3a1661817 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -UpSQzyXGUhMfedYIh48ih8GJ_CBT2cJLH4vlZjnNw-YC +c5padahsa9sMecBb3fCiLz1kXQT9HGF7PQ8ULJvs8uwC From 0571df9befcc4dbc9b6cae7bf3d6c7aeccd08e38 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sat, 16 Nov 2024 17:22:34 -0500 Subject: [PATCH 105/386] Roll Flutter Engine from 908061196148 to 40000c742910 (1 revision) (#159038) https://github.com/flutter/engine/compare/908061196148...40000c742910 2024-11-16 skia-flutter-autoroll@skia.org Roll Dart SDK from d47c22e5f63a to dfa7b3ac976b (1 revision) (flutter/engine#56649) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 058642ae4e4..97156718e6d 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -9080611961485256a1eead107ace976cbcd2f070 +40000c7429106c8cfd8abdbe117e13f5c899b785 From c2309f3a9e82d398b3ec7cbfac4bd0f31a416e7f Mon Sep 17 00:00:00 2001 From: Christofer Date: Sat, 16 Nov 2024 14:24:39 -0800 Subject: [PATCH 106/386] Fix NavigationBar example overflow alignment (#159034) Fix the NavigationBar example overflow alignment. ### Before: ### After: *List which issues are fixed by this PR. You must list at least one issue. An issue is not required if the PR fixes something trivial like a typo.* *If you had to change anything in the [flutter/tests] repo, include a link to the migration guide as per the [breaking change policy].* ## Pre-launch Checklist - [X] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [X] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [X] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [X] I listed at least one issue that this PR fixes in the description above. - [X] I updated/added relevant documentation (doc comments with `///`). - [X] I added new tests to check the change I am making, or this PR is [test-exempt]. - [X] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [X] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- .../material/navigation_bar/navigation_bar.1.dart | 2 ++ .../navigation_bar/navigation_bar.1_test.dart | 13 ++++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) 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/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); }); } From 2a966d3c534492bfbbc3cd392cf2b535284004f9 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sat, 16 Nov 2024 22:20:29 -0500 Subject: [PATCH 107/386] Roll Flutter Engine from 40000c742910 to 6f9854ad6ed7 (2 revisions) (#159041) https://github.com/flutter/engine/compare/40000c742910...6f9854ad6ed7 2024-11-17 skia-flutter-autoroll@skia.org Roll Dart SDK from dfa7b3ac976b to 8795a3eaa87b (1 revision) (flutter/engine#56652) 2024-11-16 skia-flutter-autoroll@skia.org Roll Skia from f8ec97344733 to b88c7b03a838 (1 revision) (flutter/engine#56651) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 97156718e6d..6f6a7af07b5 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -40000c7429106c8cfd8abdbe117e13f5c899b785 +6f9854ad6ed71cfed90611e68849e3cf39077905 From 83ee53767f1fb08bae42988dfdfdd5afa3a56e13 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sun, 17 Nov 2024 05:16:26 -0500 Subject: [PATCH 108/386] Roll Flutter Engine from 6f9854ad6ed7 to 9d0720a7b0ec (2 revisions) (#159047) https://github.com/flutter/engine/compare/6f9854ad6ed7...9d0720a7b0ec 2024-11-17 skia-flutter-autoroll@skia.org Roll Skia from b88c7b03a838 to 1086e39c04cf (1 revision) (flutter/engine#56654) 2024-11-17 chris@bracken.jp iOS: Eliminate FlutterEngine dealloc notification (flutter/engine#56650) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 6f6a7af07b5..1a3b6667f6e 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -6f9854ad6ed71cfed90611e68849e3cf39077905 +9d0720a7b0ec758a1f30a0e0c90c6595250bfe21 From 012f6b34c60c259d543e8ad58f130821161ec1cc Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sun, 17 Nov 2024 06:34:08 -0500 Subject: [PATCH 109/386] Roll Flutter Engine from 9d0720a7b0ec to 4c1eb8cacb95 (1 revision) (#159049) https://github.com/flutter/engine/compare/9d0720a7b0ec...4c1eb8cacb95 2024-11-17 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from c5padahsa9sMecBb3... to K-3yXpPmmu1f0idCa... (flutter/engine#56656) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from c5padahsa9sM to K-3yXpPmmu1f If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 1a3b6667f6e..48b141d28d2 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -9d0720a7b0ec758a1f30a0e0c90c6595250bfe21 +4c1eb8cacb95fa175dd86136573bf37e8e9d878a diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index ff3a1661817..be8db3b93dc 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -c5padahsa9sMecBb3fCiLz1kXQT9HGF7PQ8ULJvs8uwC +K-3yXpPmmu1f0idCavBG1eJFQAwaYDDwyoAEJib6yV0C From 41c273f8c66c4a5a373cea8b13605c6d7c813829 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sun, 17 Nov 2024 09:12:30 -0500 Subject: [PATCH 110/386] Roll Flutter Engine from 4c1eb8cacb95 to 4878f1c9ed1c (1 revision) (#159050) https://github.com/flutter/engine/compare/4c1eb8cacb95...4878f1c9ed1c 2024-11-17 skia-flutter-autoroll@skia.org Roll Skia from 1086e39c04cf to 4708534db2e7 (1 revision) (flutter/engine#56657) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 48b141d28d2..ccfc06fed9b 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -4c1eb8cacb95fa175dd86136573bf37e8e9d878a +4878f1c9ed1cebbc19cab7133f99cc904e65ef0e From dc44547d0d90dfff4fd4c3bdcd525f9d7a70744e Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sun, 17 Nov 2024 21:16:40 -0500 Subject: [PATCH 111/386] Roll Flutter Engine from 4878f1c9ed1c to a63841d0c64b (8 revisions) (#159057) https://github.com/flutter/engine/compare/4878f1c9ed1c...a63841d0c64b 2024-11-18 chris@bracken.jp iOS: Clean up @synthesize directives / ivars (flutter/engine#56665) 2024-11-17 skia-flutter-autoroll@skia.org Roll Skia from 4708534db2e7 to 452208ce96aa (1 revision) (flutter/engine#56664) 2024-11-17 chris@bracken.jp iOS: Extract constant for CADisableMinimumFrameDurationOnPhone (flutter/engine#56659) 2024-11-17 chris@bracken.jp iOS: Eliminate unnecessary use of NSClassFromString (flutter/engine#56660) 2024-11-17 chris@bracken.jp iOS: Eliminate unnecessary bridged retain casts (flutter/engine#56662) 2024-11-17 chris@bracken.jp iOS,macOS: Fix string constant declarations (flutter/engine#56661) 2024-11-17 chris@bracken.jp iOS: Make FlutterViewController.engine a strong ref (flutter/engine#56663) 2024-11-17 chris@bracken.jp iOS: Clean up uses of string literal constants (flutter/engine#56658) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index ccfc06fed9b..3d5117a55a8 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -4878f1c9ed1cebbc19cab7133f99cc904e65ef0e +a63841d0c64bfd2b91fe383a4c6859c60044ac68 From b3818f6b59791da804d203775710f7b4e3a439e0 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Mon, 18 Nov 2024 05:49:32 -0500 Subject: [PATCH 112/386] Roll Flutter Engine from a63841d0c64b to f365c9f5dce3 (1 revision) (#159064) https://github.com/flutter/engine/compare/a63841d0c64b...f365c9f5dce3 2024-11-18 skia-flutter-autoroll@skia.org Roll Skia from 452208ce96aa to 5968000526fe (3 revisions) (flutter/engine#56671) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 3d5117a55a8..c15d388d183 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -a63841d0c64bfd2b91fe383a4c6859c60044ac68 +f365c9f5dce3e0831994735158c6b99254303852 From e06d66ae9aacedd6615a29158e36145936c73854 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Mon, 18 Nov 2024 10:45:29 -0500 Subject: [PATCH 113/386] Roll Packages from b164be312ca2 to c1eabf5e32cc (6 revisions) (#159077) https://github.com/flutter/packages/compare/b164be312ca2...c1eabf5e32cc 2024-11-16 49699333+dependabot[bot]@users.noreply.github.com [gradle]: Bump org.mockito.kotlin:mockito-kotlin from 4.1.0 to 5.4.0 in /packages/interactive_media_ads/android (flutter/packages#8095) 2024-11-16 kevmoo@users.noreply.github.com [google_identity_services_web] Migrate all types to JSObject (flutter/packages#8053) 2024-11-15 49699333+dependabot[bot]@users.noreply.github.com [file_selector]: Bump androidx.annotation:annotation from 1.9.0 to 1.9.1 in /packages/file_selector/file_selector_android/android (flutter/packages#7982) 2024-11-15 ditman@gmail.com [web_benchmarks] Remove `WebRenderer` enum. (flutter/packages#8103) 2024-11-15 kevmoo@users.noreply.github.com [google_maps_flutter] Fix detection of WebAssembly compatibility (flutter/packages#8102) 2024-11-15 engine-flutter-autoroll@skia.org Roll Flutter from ed553d10cf63 to 0e2d55e0e7b2 (40 revisions) (flutter/packages#8106) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-packages-flutter-autoroll Please CC flutter-ecosystem@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/flutter_packages.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/flutter_packages.version b/bin/internal/flutter_packages.version index 3bedfae07be..ec2c735f144 100644 --- a/bin/internal/flutter_packages.version +++ b/bin/internal/flutter_packages.version @@ -1 +1 @@ -b164be312ca2e45ea332e38dd278ac84abe7658f +c1eabf5e32cccfe54474726584ea1c2cf5a0a269 From 6d45f7595854ddefbbc5a577a30554853826f6cb Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Mon, 18 Nov 2024 11:21:10 -0500 Subject: [PATCH 114/386] Roll Flutter Engine from f365c9f5dce3 to e1f4e7d9bfc4 (4 revisions) (#159078) https://github.com/flutter/engine/compare/f365c9f5dce3...e1f4e7d9bfc4 2024-11-18 skia-flutter-autoroll@skia.org Roll Dart SDK from 8795a3eaa87b to ae5111067032 (1 revision) (flutter/engine#56675) 2024-11-18 skia-flutter-autoroll@skia.org Roll Skia from 5968000526fe to 78fd0dfa6cf8 (1 revision) (flutter/engine#56674) 2024-11-18 kjlubick@users.noreply.github.com Use updated gni source list (flutter/engine#56627) 2024-11-18 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from K-3yXpPmmu1f0idCa... to io00npG_eDCYC7bac... (flutter/engine#56673) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from K-3yXpPmmu1f to io00npG_eDCY If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index c15d388d183..868407e46e5 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -f365c9f5dce3e0831994735158c6b99254303852 +e1f4e7d9bfc429881c6b5241dab6c7c18b58bf1e diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index be8db3b93dc..6ce43794467 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -K-3yXpPmmu1f0idCavBG1eJFQAwaYDDwyoAEJib6yV0C +io00npG_eDCYC7bac6n1mLVKsJeKcBYdTUP0KLI7FvAC From 0d0bf35b21f0890c4ede7749392b9a281e50f821 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Mon, 18 Nov 2024 12:14:23 -0500 Subject: [PATCH 115/386] Roll Flutter Engine from e1f4e7d9bfc4 to 9686de154114 (1 revision) (#159082) https://github.com/flutter/engine/compare/e1f4e7d9bfc4...9686de154114 2024-11-18 skia-flutter-autoroll@skia.org Roll Skia from 78fd0dfa6cf8 to 7594233ff914 (1 revision) (flutter/engine#56677) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 868407e46e5..ef56311a2ba 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -e1f4e7d9bfc429881c6b5241dab6c7c18b58bf1e +9686de154114bc3f487aec34ba0a4f6a8a6358ef From 74384004ce93e5fda70bfaf05bc9476c3ccf3e64 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Mon, 18 Nov 2024 10:22:24 -0800 Subject: [PATCH 116/386] No longer download `android-x86-jit-release`. (#159011) Unblocks https://github.com/flutter/flutter/issues/151610. --- packages/flutter_tools/lib/src/flutter_cache.dart | 1 - 1 file changed, 1 deletion(-) 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 = > [ From 03c13af0b412744f62529345b0f58d84e0eb4709 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Mon, 18 Nov 2024 11:00:04 -0800 Subject: [PATCH 117/386] Define and use `flutterBin` consistently across `integration.shard`. (#159007) Towards https://github.com/flutter/flutter/issues/158875. This should be a NOP, and just reduce the amount of copy-pasted code across tests. --- .../integration.shard/analyze_size_test.dart | 6 ------ .../integration.shard/android_e2e_api_test.dart | 1 - .../android_gradle_daemon_cache_test.dart | 2 -- ...roid_gradle_deprecated_plugin_apply_test.dart | 2 -- .../android_gradle_flutter_source_path_test.dart | 5 ----- .../android_gradle_java_version_test.dart | 2 -- ...flutter_plugins_strings_in_comments_test.dart | 6 ------ ...id_gradle_outputs_app_link_settings_test.dart | 4 ---- ...android_gradle_print_build_variants_test.dart | 2 -- ...d_plugin_compilesdkversion_mismatch_test.dart | 6 ------ .../android_plugin_example_app_build_test.dart | 6 ------ .../android_plugin_ndkversion_mismatch_test.dart | 6 ------ .../android_plugin_new_output_dir_test.dart | 5 ----- .../android_plugin_skip_unsupported_test.dart | 6 ------ .../asset_transformation_test.dart | 5 ----- .../build_ios_config_only_test.dart | 1 - .../build_macos_config_only_test.dart | 1 - .../integration.shard/build_preview_test.dart | 1 - .../integration.shard/command_output_test.dart | 16 ---------------- .../test/integration.shard/daemon_mode_test.dart | 2 -- .../deferred_components_test.dart | 7 ------- .../deprecated_gradle_settings_test.dart | 1 - .../integration.shard/devtools_uri_test.dart | 1 - .../downgrade_upgrade_integration_test.dart | 1 - ..._build_android_app_project_builddir_test.dart | 6 ------ .../flutter_build_apk_verbose_test.dart | 6 ------ .../flutter_build_config_only_test.dart | 6 ------ .../flutter_build_wasm_test.dart | 6 ------ .../flutter_build_windows_test.dart | 6 ------ ...lutter_build_with_compilation_error_test.dart | 6 ------ .../flutter_plugins_dependencies_test.dart | 3 --- .../test/integration.shard/flutter_run_test.dart | 1 - .../flutter_run_with_error_test.dart | 6 ------ .../gradle_non_android_plugin_test.dart | 6 ------ .../isolated/native_assets_agp_version_test.dart | 2 +- .../isolated/native_assets_test.dart | 2 +- .../isolated/native_assets_test_utils.dart | 2 +- ...tive_assets_without_cbuild_assemble_test.dart | 1 - .../integration.shard/observatory_port_test.dart | 3 --- .../swift_package_manager_create_app_test.dart | 6 ------ ...swift_package_manager_create_plugin_test.dart | 6 ------ .../swift_package_manager_test.dart | 6 ------ .../test/integration.shard/test_driver.dart | 1 - .../test/integration.shard/test_test.dart | 1 - .../test/integration.shard/test_utils.dart | 7 +++++++ .../integration.shard/transition_test_utils.dart | 3 +-- 46 files changed, 11 insertions(+), 176 deletions(-) diff --git a/packages/flutter_tools/test/integration.shard/analyze_size_test.dart b/packages/flutter_tools/test/integration.shard/analyze_size_test.dart index 13e85cb5e74..f7a12ec4a84 100644 --- a/packages/flutter_tools/test/integration.shard/analyze_size_test.dart +++ b/packages/flutter_tools/test/integration.shard/analyze_size_test.dart @@ -20,7 +20,6 @@ const String runDevToolsMessage = 'dart devtools '; void main() { testWithoutContext('--analyze-size flag produces expected output on hello_world for Android', () async { final String workingDirectory = fileSystem.path.join(getFlutterRoot(), 'examples', 'hello_world'); - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final ProcessResult result = await processManager.run([ flutterBin, 'build', @@ -53,7 +52,6 @@ void main() { testWithoutContext('--analyze-size flag produces expected output on hello_world for iOS', () async { final String workingDirectory = fileSystem.path.join(getFlutterRoot(), 'examples', 'hello_world'); - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('flutter_size_test.'); final Directory codeSizeDir = tempDir.childDirectory('code size dir')..createSync(); final ProcessResult result = await processManager.run([ @@ -91,7 +89,6 @@ void main() { testWithoutContext('--analyze-size flag produces expected output on hello_world for macOS', () async { final String workingDirectory = fileSystem.path.join(getFlutterRoot(), 'examples', 'hello_world'); - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('flutter_size_test.'); final Directory codeSizeDir = tempDir.childDirectory('code size dir')..createSync(); @@ -143,7 +140,6 @@ void main() { }, skip: !platform.isMacOS); // [intended] this is a macos only test. testWithoutContext('--analyze-size is only supported in release mode', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final ProcessResult result = await processManager.run([ flutterBin, 'build', @@ -163,7 +159,6 @@ void main() { }); testWithoutContext('--analyze-size is not supported in combination with --split-debug-info', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final List command = [ flutterBin, 'build', @@ -188,7 +183,6 @@ void main() { }); testWithoutContext('--analyze-size allows overriding the directory for code size files', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('flutter_size_test.'); final List command = [ diff --git a/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart b/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart index 9c1c677f6a7..599f66a6060 100644 --- a/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart @@ -24,7 +24,6 @@ void main() { }); testWithoutContext('build succeeds with api 33 features', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); ProcessResult result = await processManager.run([ flutterBin, 'create', diff --git a/packages/flutter_tools/test/integration.shard/android_gradle_daemon_cache_test.dart b/packages/flutter_tools/test/integration.shard/android_gradle_daemon_cache_test.dart index b9b3af1db55..3b42601b196 100644 --- a/packages/flutter_tools/test/integration.shard/android_gradle_daemon_cache_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_gradle_daemon_cache_test.dart @@ -22,8 +22,6 @@ void main() { testWithoutContext( 'gradle task succeeds when adding plugins with gradle daemon enabled', () async { - final String flutterBin = - fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final Directory appDir = tempDir.childDirectory('testapp'); final Directory androidDir = appDir.childDirectory('android'); diff --git a/packages/flutter_tools/test/integration.shard/android_gradle_deprecated_plugin_apply_test.dart b/packages/flutter_tools/test/integration.shard/android_gradle_deprecated_plugin_apply_test.dart index 91bc50622af..20221f174b6 100644 --- a/packages/flutter_tools/test/integration.shard/android_gradle_deprecated_plugin_apply_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_gradle_deprecated_plugin_apply_test.dart @@ -28,8 +28,6 @@ void main() { testWithoutContext( 'gradle prints warning when Flutter\'s Gradle plugins are applied using deprecated "apply plugin" way', () async { // Create a new flutter project. - final String flutterBin = - fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); ProcessResult result = await processManager.run([ flutterBin, 'create', diff --git a/packages/flutter_tools/test/integration.shard/android_gradle_flutter_source_path_test.dart b/packages/flutter_tools/test/integration.shard/android_gradle_flutter_source_path_test.dart index 814cdfec9ab..929cbb022c3 100644 --- a/packages/flutter_tools/test/integration.shard/android_gradle_flutter_source_path_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_gradle_flutter_source_path_test.dart @@ -29,11 +29,6 @@ void main() { final Project project = DeferredComponentsProject( MissingFlutterSourcePathDeferredComponentsConfig(), ); - final String flutterBin = fileSystem.path.join( - getFlutterRoot(), - 'bin', - 'flutter', - ); final Directory exampleAppDir = tempDir.childDirectory('example'); await project.setUpIn(exampleAppDir); diff --git a/packages/flutter_tools/test/integration.shard/android_gradle_java_version_test.dart b/packages/flutter_tools/test/integration.shard/android_gradle_java_version_test.dart index 6dea44867ad..2c42f413c86 100644 --- a/packages/flutter_tools/test/integration.shard/android_gradle_java_version_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_gradle_java_version_test.dart @@ -24,8 +24,6 @@ void main() { testWithoutContext( 'gradle task exists named javaVersion that prints jdk version', () async { // Create a new flutter project. - final String flutterBin = - fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); ProcessResult result = await processManager.run([ flutterBin, 'create', diff --git a/packages/flutter_tools/test/integration.shard/android_gradle_legacy_flutter_plugins_strings_in_comments_test.dart b/packages/flutter_tools/test/integration.shard/android_gradle_legacy_flutter_plugins_strings_in_comments_test.dart index 041b3aa4538..4daf82441ae 100644 --- a/packages/flutter_tools/test/integration.shard/android_gradle_legacy_flutter_plugins_strings_in_comments_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_gradle_legacy_flutter_plugins_strings_in_comments_test.dart @@ -28,12 +28,6 @@ void main() { }); test('should build Android app with commented-out ".flutter-plugins" in settings.gradle', () async { - final String flutterBin = fileSystem.path.join( - getFlutterRoot(), - 'bin', - 'flutter', - ); - // Create Android app project instead of plugin processManager.runSync([ flutterBin, diff --git a/packages/flutter_tools/test/integration.shard/android_gradle_outputs_app_link_settings_test.dart b/packages/flutter_tools/test/integration.shard/android_gradle_outputs_app_link_settings_test.dart index 60788ae9dc9..ea1521fd39c 100644 --- a/packages/flutter_tools/test/integration.shard/android_gradle_outputs_app_link_settings_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_gradle_outputs_app_link_settings_test.dart @@ -278,8 +278,6 @@ void main() { testWithoutContext( 'gradle task outputsAppLinkSettings works when a project has app links', () async { // Create a new flutter project. - final String flutterBin = - fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); ProcessResult result = await processManager.run([ flutterBin, 'create', @@ -345,8 +343,6 @@ void main() { testWithoutContext( 'gradle task outputsAppLinkSettings works when a project does not have app link and the flutter_deeplinking_enabled flag', () async { // Create a new flutter project. - final String flutterBin = - fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); ProcessResult result = await processManager.run([ flutterBin, 'create', diff --git a/packages/flutter_tools/test/integration.shard/android_gradle_print_build_variants_test.dart b/packages/flutter_tools/test/integration.shard/android_gradle_print_build_variants_test.dart index fa2c72359fe..e8f60aff814 100644 --- a/packages/flutter_tools/test/integration.shard/android_gradle_print_build_variants_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_gradle_print_build_variants_test.dart @@ -31,8 +31,6 @@ void main() { testWithoutContext( 'gradle task exists named printBuildVariants that prints build variants', () async { // Create a new flutter project. - final String flutterBin = - fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); ProcessResult result = await processManager.run([ flutterBin, 'create', diff --git a/packages/flutter_tools/test/integration.shard/android_plugin_compilesdkversion_mismatch_test.dart b/packages/flutter_tools/test/integration.shard/android_plugin_compilesdkversion_mismatch_test.dart index 301e851e71e..d7cc48282fe 100644 --- a/packages/flutter_tools/test/integration.shard/android_plugin_compilesdkversion_mismatch_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_plugin_compilesdkversion_mismatch_test.dart @@ -24,12 +24,6 @@ void main() { }); test('error logged when plugin Android compileSdk version higher than project', () async { - final String flutterBin = fileSystem.path.join( - getFlutterRoot(), - 'bin', - 'flutter', - ); - // Create dummy plugin processManager.runSync([ flutterBin, diff --git a/packages/flutter_tools/test/integration.shard/android_plugin_example_app_build_test.dart b/packages/flutter_tools/test/integration.shard/android_plugin_example_app_build_test.dart index 8bb28785faf..67a70cf04ea 100644 --- a/packages/flutter_tools/test/integration.shard/android_plugin_example_app_build_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_plugin_example_app_build_test.dart @@ -32,12 +32,6 @@ void main() { required String template, required Directory tempDir, }) async { - final String flutterBin = fileSystem.path.join( - getFlutterRoot(), - 'bin', - 'flutter', - ); - final String testName = '${template}_test'; ProcessResult result = processManager.runSync([ diff --git a/packages/flutter_tools/test/integration.shard/android_plugin_ndkversion_mismatch_test.dart b/packages/flutter_tools/test/integration.shard/android_plugin_ndkversion_mismatch_test.dart index 21784f1b5ee..e685c76efe8 100644 --- a/packages/flutter_tools/test/integration.shard/android_plugin_ndkversion_mismatch_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_plugin_ndkversion_mismatch_test.dart @@ -23,12 +23,6 @@ void main() { }); test('error logged when plugin Android ndkVersion higher than project', () async { - final String flutterBin = fileSystem.path.join( - getFlutterRoot(), - 'bin', - 'flutter', - ); - // Create dummy plugin processManager.runSync([ flutterBin, diff --git a/packages/flutter_tools/test/integration.shard/android_plugin_new_output_dir_test.dart b/packages/flutter_tools/test/integration.shard/android_plugin_new_output_dir_test.dart index 24525887652..3daa47b4c6e 100644 --- a/packages/flutter_tools/test/integration.shard/android_plugin_new_output_dir_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_plugin_new_output_dir_test.dart @@ -26,11 +26,6 @@ void main() { }); test('plugins use individualized build directories based on their name.', () async { - final String flutterBin = fileSystem.path.join( - getFlutterRoot(), - 'bin', - 'flutter', - ); // create flutter module project ProcessResult result = processManager.runSync([ flutterBin, diff --git a/packages/flutter_tools/test/integration.shard/android_plugin_skip_unsupported_test.dart b/packages/flutter_tools/test/integration.shard/android_plugin_skip_unsupported_test.dart index 297dc6a725f..89e768bb578 100644 --- a/packages/flutter_tools/test/integration.shard/android_plugin_skip_unsupported_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_plugin_skip_unsupported_test.dart @@ -37,12 +37,6 @@ void main() { required Project project, required bool createAndroidPluginFolder, }) async { - final String flutterBin = fileSystem.path.join( - getFlutterRoot(), - 'bin', - 'flutter', - ); - // Create dummy plugin that supports iOS and optionally Android. processManager.runSync([ flutterBin, diff --git a/packages/flutter_tools/test/integration.shard/asset_transformation_test.dart b/packages/flutter_tools/test/integration.shard/asset_transformation_test.dart index e53ea82b08d..5e1ba07fc4b 100644 --- a/packages/flutter_tools/test/integration.shard/asset_transformation_test.dart +++ b/packages/flutter_tools/test/integration.shard/asset_transformation_test.dart @@ -67,11 +67,6 @@ Future main() async { ..createSync(recursive: true) ..writeAsStringSync('abc'); - final String flutterBin = fileSystem.path.join( - getFlutterRoot(), - 'bin', - 'flutter', - ); final ProcessResult result = await processManager.run( [ flutterBin, diff --git a/packages/flutter_tools/test/integration.shard/build_ios_config_only_test.dart b/packages/flutter_tools/test/integration.shard/build_ios_config_only_test.dart index 86adcfba17f..997f62e5d0b 100644 --- a/packages/flutter_tools/test/integration.shard/build_ios_config_only_test.dart +++ b/packages/flutter_tools/test/integration.shard/build_ios_config_only_test.dart @@ -17,7 +17,6 @@ void main() { 'integration_tests', 'flutter_gallery', ); - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); await processManager.run([ flutterBin, diff --git a/packages/flutter_tools/test/integration.shard/build_macos_config_only_test.dart b/packages/flutter_tools/test/integration.shard/build_macos_config_only_test.dart index 6fd271c55aa..500239a16fe 100644 --- a/packages/flutter_tools/test/integration.shard/build_macos_config_only_test.dart +++ b/packages/flutter_tools/test/integration.shard/build_macos_config_only_test.dart @@ -17,7 +17,6 @@ void main() { 'integration_tests', 'flutter_gallery', ); - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); await processManager.run([ flutterBin, diff --git a/packages/flutter_tools/test/integration.shard/build_preview_test.dart b/packages/flutter_tools/test/integration.shard/build_preview_test.dart index f1d3f377041..cff31bb8497 100644 --- a/packages/flutter_tools/test/integration.shard/build_preview_test.dart +++ b/packages/flutter_tools/test/integration.shard/build_preview_test.dart @@ -18,7 +18,6 @@ void main() { late Directory tempDir; final FileSystem fs = LocalFileSystemBlockingSetCurrentDirectory(); - final String flutterBin = fs.path.join(getFlutterRoot(), 'bin', 'flutter'); final File previewBin = fs .directory(getFlutterRoot()) .childDirectory('bin') diff --git a/packages/flutter_tools/test/integration.shard/command_output_test.dart b/packages/flutter_tools/test/integration.shard/command_output_test.dart index b03b64801b7..8b1021155a8 100644 --- a/packages/flutter_tools/test/integration.shard/command_output_test.dart +++ b/packages/flutter_tools/test/integration.shard/command_output_test.dart @@ -16,7 +16,6 @@ import 'test_utils.dart'; void main() { testWithoutContext('All development tools and deprecated commands are hidden and help text is not verbose', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final ProcessResult result = await processManager.run([ flutterBin, '-h', @@ -34,7 +33,6 @@ void main() { }); testWithoutContext('Flutter help is shown with -? command line argument', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final ProcessResult result = await processManager.run([ flutterBin, '-?', @@ -48,7 +46,6 @@ void main() { }); testWithoutContext('flutter doctor is not verbose', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final ProcessResult result = await processManager.run([ flutterBin, 'doctor', @@ -60,7 +57,6 @@ void main() { }); testWithoutContext('flutter doctor -vv super verbose', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final ProcessResult result = await processManager.run([ flutterBin, 'doctor', @@ -72,7 +68,6 @@ void main() { }); testWithoutContext('flutter config --list contains all features', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final ProcessResult result = await processManager.run([ flutterBin, 'config', @@ -99,7 +94,6 @@ void main() { .childDirectory('lib') .childFile('main.dart') .createSync(recursive: true); - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final ProcessResult result = await processManager.run([ flutterBin, 'run', @@ -115,7 +109,6 @@ void main() { }); testWithoutContext('flutter attach --machine uses AppRunLogger', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final ProcessResult result = await processManager.run([ flutterBin, 'attach', @@ -127,7 +120,6 @@ void main() { }); testWithoutContext('flutter --version --machine outputs JSON with flutterRoot', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final ProcessResult result = await processManager.run([ flutterBin, '--version', @@ -145,7 +137,6 @@ void main() { testWithoutContext('A tool exit is thrown for an invalid debug-url in flutter attach', () async { // This test is almost exactly like the next one; update them together please. - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final String helloWorld = fileSystem.path.join(getFlutterRoot(), 'examples', 'hello_world'); final ProcessResult result = await processManager.run([ flutterBin, @@ -164,7 +155,6 @@ void main() { testWithoutContext('--debug-uri is an alias for --debug-url', () async { // This text is exactly the same as the previous one but with a "l" turned to an "i". - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final String helloWorld = fileSystem.path.join(getFlutterRoot(), 'examples', 'hello_world'); final ProcessResult result = await processManager.run([ flutterBin, @@ -186,8 +176,6 @@ void main() { }); testWithoutContext('will load bootstrap script before starting', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); - final File bootstrap = fileSystem.file(fileSystem.path.join( getFlutterRoot(), 'bin', @@ -208,7 +196,6 @@ void main() { }); testWithoutContext('Providing sksl bundle with missing file with tool exit', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final String helloWorld = fileSystem.path.join(getFlutterRoot(), 'examples', 'hello_world'); final ProcessResult result = await processManager.run([ flutterBin, @@ -224,7 +211,6 @@ void main() { }); testWithoutContext('flutter attach does not support --release', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final String helloWorld = fileSystem.path.join(getFlutterRoot(), 'examples', 'hello_world'); final ProcessResult result = await processManager.run([ flutterBin, @@ -238,7 +224,6 @@ void main() { }); testWithoutContext('flutter can report crashes', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final ProcessResult result = await processManager.run([ flutterBin, 'update-packages', @@ -255,7 +240,6 @@ void main() { }); testWithoutContext('flutter supports trailing args', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final String helloWorld = fileSystem.path.join(getFlutterRoot(), 'examples', 'hello_world'); final ProcessResult result = await processManager.run([ flutterBin, diff --git a/packages/flutter_tools/test/integration.shard/daemon_mode_test.dart b/packages/flutter_tools/test/integration.shard/daemon_mode_test.dart index c8d4b3952b8..eb8655d8021 100644 --- a/packages/flutter_tools/test/integration.shard/daemon_mode_test.dart +++ b/packages/flutter_tools/test/integration.shard/daemon_mode_test.dart @@ -31,8 +31,6 @@ void main() { final BasicProject project = BasicProject(); await project.setUpIn(tempDir); - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); - const ProcessManager processManager = LocalProcessManager(); daemonProcess = await processManager.start( [flutterBin, ...getLocalEngineArguments(), '--show-test-device', 'daemon'], diff --git a/packages/flutter_tools/test/integration.shard/deferred_components_test.dart b/packages/flutter_tools/test/integration.shard/deferred_components_test.dart index f01ea24bf59..0402e8d4d7c 100644 --- a/packages/flutter_tools/test/integration.shard/deferred_components_test.dart +++ b/packages/flutter_tools/test/integration.shard/deferred_components_test.dart @@ -30,7 +30,6 @@ void main() { testWithoutContext('simple build appbundle android-arm64 target succeeds', () async { final DeferredComponentsProject project = DeferredComponentsProject(BasicDeferredComponentsConfig()); await project.setUpIn(tempDir); - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final ProcessResult result = await processManager.run([ flutterBin, ...getLocalEngineArguments(), @@ -64,7 +63,6 @@ void main() { testWithoutContext('simple build appbundle all targets succeeds', () async { final DeferredComponentsProject project = DeferredComponentsProject(BasicDeferredComponentsConfig()); await project.setUpIn(tempDir); - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final ProcessResult result = await processManager.run([ flutterBin, ...getLocalEngineArguments(), @@ -109,7 +107,6 @@ void main() { testWithoutContext('simple build appbundle no-deferred-components succeeds', () async { final DeferredComponentsProject project = DeferredComponentsProject(BasicDeferredComponentsConfig()); await project.setUpIn(tempDir); - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final ProcessResult result = await processManager.run([ flutterBin, ...getLocalEngineArguments(), @@ -153,7 +150,6 @@ void main() { testWithoutContext('simple build appbundle mismatched golden no-validate-deferred-components succeeds', () async { final DeferredComponentsProject project = DeferredComponentsProject(MismatchedGoldenDeferredComponentsConfig()); await project.setUpIn(tempDir); - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final ProcessResult result = await processManager.run([ flutterBin, ...getLocalEngineArguments(), @@ -199,7 +195,6 @@ void main() { testWithoutContext('simple build appbundle missing android dynamic feature module fails', () async { final DeferredComponentsProject project = DeferredComponentsProject(NoAndroidDynamicFeatureModuleDeferredComponentsConfig()); await project.setUpIn(tempDir); - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final ProcessResult result = await processManager.run([ flutterBin, ...getLocalEngineArguments(), @@ -221,7 +216,6 @@ void main() { testWithoutContext('simple build appbundle missing golden fails', () async { final DeferredComponentsProject project = DeferredComponentsProject(NoGoldenDeferredComponentsConfig()); await project.setUpIn(tempDir); - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final ProcessResult result = await processManager.run([ flutterBin, ...getLocalEngineArguments(), @@ -243,7 +237,6 @@ void main() { testWithoutContext('simple build appbundle mismatched golden fails', () async { final DeferredComponentsProject project = DeferredComponentsProject(MismatchedGoldenDeferredComponentsConfig()); await project.setUpIn(tempDir); - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final ProcessResult result = await processManager.run([ flutterBin, ...getLocalEngineArguments(), diff --git a/packages/flutter_tools/test/integration.shard/deprecated_gradle_settings_test.dart b/packages/flutter_tools/test/integration.shard/deprecated_gradle_settings_test.dart index 95eb7302a8c..50e5b21af3d 100644 --- a/packages/flutter_tools/test/integration.shard/deprecated_gradle_settings_test.dart +++ b/packages/flutter_tools/test/integration.shard/deprecated_gradle_settings_test.dart @@ -15,7 +15,6 @@ import 'test_utils.dart'; void main() { test('android project using deprecated settings.gradle will still build', () async { final String workingDirectory = fileSystem.path.join(getFlutterRoot(), 'dev', 'integration_tests', 'gradle_deprecated_settings'); - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final File settingsDotGradleFile = fileSystem.file( fileSystem.path.join(workingDirectory, 'android', 'settings.gradle')); diff --git a/packages/flutter_tools/test/integration.shard/devtools_uri_test.dart b/packages/flutter_tools/test/integration.shard/devtools_uri_test.dart index af15861554e..5da292df5b6 100644 --- a/packages/flutter_tools/test/integration.shard/devtools_uri_test.dart +++ b/packages/flutter_tools/test/integration.shard/devtools_uri_test.dart @@ -30,7 +30,6 @@ void main() { final Completer completer = Completer(); const String matcher = 'The Flutter DevTools debugger and profiler on'; - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final Process process = await processManager.start([ flutterBin, 'run', diff --git a/packages/flutter_tools/test/integration.shard/downgrade_upgrade_integration_test.dart b/packages/flutter_tools/test/integration.shard/downgrade_upgrade_integration_test.dart index 20b7675b78a..0775a0ecb88 100644 --- a/packages/flutter_tools/test/integration.shard/downgrade_upgrade_integration_test.dart +++ b/packages/flutter_tools/test/integration.shard/downgrade_upgrade_integration_test.dart @@ -23,7 +23,6 @@ final BufferLogger logger = BufferLogger.test( outputPreferences: OutputPreferences.test(wrapText: true), ); final ProcessUtils processUtils = ProcessUtils(processManager: processManager, logger: logger); -final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', platform.isWindows ? 'flutter.bat' : 'flutter'); /// A test for flutter upgrade & downgrade that checks out a parallel flutter repo. void main() { diff --git a/packages/flutter_tools/test/integration.shard/flutter_build_android_app_project_builddir_test.dart b/packages/flutter_tools/test/integration.shard/flutter_build_android_app_project_builddir_test.dart index 2f71f983dc8..1a09cdf7e5c 100644 --- a/packages/flutter_tools/test/integration.shard/flutter_build_android_app_project_builddir_test.dart +++ b/packages/flutter_tools/test/integration.shard/flutter_build_android_app_project_builddir_test.dart @@ -16,16 +16,10 @@ import 'test_utils.dart'; // project in the test. void main() { late Directory tempDir; - late String flutterBin; late Directory exampleAppDir; setUp(() async { tempDir = createResolvedTempDirectorySync('flutter_plugin_test.'); - flutterBin = fileSystem.path.join( - getFlutterRoot(), - 'bin', - 'flutter', - ); exampleAppDir = tempDir.childDirectory('aaa').childDirectory('example'); processManager.runSync([ diff --git a/packages/flutter_tools/test/integration.shard/flutter_build_apk_verbose_test.dart b/packages/flutter_tools/test/integration.shard/flutter_build_apk_verbose_test.dart index 4a5c253cc6a..c4751936faf 100644 --- a/packages/flutter_tools/test/integration.shard/flutter_build_apk_verbose_test.dart +++ b/packages/flutter_tools/test/integration.shard/flutter_build_apk_verbose_test.dart @@ -11,16 +11,10 @@ import 'test_utils.dart'; // Test that verbosity it propagated to Gradle tasks correctly. void main() { late Directory tempDir; - late String flutterBin; late Directory exampleAppDir; setUp(() async { tempDir = createResolvedTempDirectorySync('flutter_build_test.'); - flutterBin = fileSystem.path.join( - getFlutterRoot(), - 'bin', - 'flutter', - ); exampleAppDir = tempDir.childDirectory('aaa').childDirectory('example'); processManager.runSync([ diff --git a/packages/flutter_tools/test/integration.shard/flutter_build_config_only_test.dart b/packages/flutter_tools/test/integration.shard/flutter_build_config_only_test.dart index 92f38142534..88ae26a244c 100644 --- a/packages/flutter_tools/test/integration.shard/flutter_build_config_only_test.dart +++ b/packages/flutter_tools/test/integration.shard/flutter_build_config_only_test.dart @@ -12,16 +12,10 @@ import 'test_utils.dart'; // Test that configOnly creates the gradlew file and does not assemble and app. void main() { late Directory tempDir; - late String flutterBin; late Directory exampleAppDir; setUp(() async { tempDir = createResolvedTempDirectorySync('flutter_build_test.'); - flutterBin = fileSystem.path.join( - getFlutterRoot(), - 'bin', - 'flutter', - ); exampleAppDir = tempDir.childDirectory('bbb').childDirectory('example'); processManager.runSync( diff --git a/packages/flutter_tools/test/integration.shard/flutter_build_wasm_test.dart b/packages/flutter_tools/test/integration.shard/flutter_build_wasm_test.dart index 2af73f7d2ab..31404c88dae 100644 --- a/packages/flutter_tools/test/integration.shard/flutter_build_wasm_test.dart +++ b/packages/flutter_tools/test/integration.shard/flutter_build_wasm_test.dart @@ -12,16 +12,10 @@ import 'test_utils.dart'; void main() { late Directory tempDir; - late String flutterBin; late Directory exampleAppDir; setUp(() async { tempDir = createResolvedTempDirectorySync('flutter_web_wasm_test.'); - flutterBin = fileSystem.path.join( - getFlutterRoot(), - 'bin', - 'flutter', - ); exampleAppDir = tempDir.childDirectory('test_app'); processManager.runSync([ diff --git a/packages/flutter_tools/test/integration.shard/flutter_build_windows_test.dart b/packages/flutter_tools/test/integration.shard/flutter_build_windows_test.dart index a7bd8ff82f8..2a93d58a7f9 100644 --- a/packages/flutter_tools/test/integration.shard/flutter_build_windows_test.dart +++ b/packages/flutter_tools/test/integration.shard/flutter_build_windows_test.dart @@ -15,18 +15,12 @@ import 'test_utils.dart'; void main() { late Directory tempDir; late Directory projectRoot; - late String flutterBin; late Directory releaseDir; late File exeFile; group('flutter build windows command', () { setUpAll(() { tempDir = createResolvedTempDirectorySync('build_windows_test.'); - flutterBin = fileSystem.path.join( - getFlutterRoot(), - 'bin', - 'flutter', - ); ProcessResult result = processManager.runSync([flutterBin, 'config', '--enable-windows-desktop', ]); diff --git a/packages/flutter_tools/test/integration.shard/flutter_build_with_compilation_error_test.dart b/packages/flutter_tools/test/integration.shard/flutter_build_with_compilation_error_test.dart index c37ec4f66cf..7c5d2aefa64 100644 --- a/packages/flutter_tools/test/integration.shard/flutter_build_with_compilation_error_test.dart +++ b/packages/flutter_tools/test/integration.shard/flutter_build_with_compilation_error_test.dart @@ -15,7 +15,6 @@ import 'test_utils.dart'; void main() { late Directory tempDir; late Directory projectRoot; - late String flutterBin; final List targetPlatforms = [ 'apk', 'web', @@ -27,11 +26,6 @@ void main() { setUpAll(() { tempDir = createResolvedTempDirectorySync('build_compilation_error_test.'); - flutterBin = fileSystem.path.join( - getFlutterRoot(), - 'bin', - 'flutter', - ); processManager.runSync([flutterBin, 'config', '--enable-macos-desktop', '--enable-windows-desktop', diff --git a/packages/flutter_tools/test/integration.shard/flutter_plugins_dependencies_test.dart b/packages/flutter_tools/test/integration.shard/flutter_plugins_dependencies_test.dart index 5939b0aa01b..7f528dc4ca5 100644 --- a/packages/flutter_tools/test/integration.shard/flutter_plugins_dependencies_test.dart +++ b/packages/flutter_tools/test/integration.shard/flutter_plugins_dependencies_test.dart @@ -30,9 +30,6 @@ void main() { '.flutter-plugins-dependencies correctly denotes project dev dependencies on all default platforms', () async { // Create Flutter project. - final String flutterBin = - fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); - await processManager.run([ flutterBin, 'create', diff --git a/packages/flutter_tools/test/integration.shard/flutter_run_test.dart b/packages/flutter_tools/test/integration.shard/flutter_run_test.dart index e3b94ed4c4f..bff3bae35cb 100644 --- a/packages/flutter_tools/test/integration.shard/flutter_run_test.dart +++ b/packages/flutter_tools/test/integration.shard/flutter_run_test.dart @@ -32,7 +32,6 @@ void main() { // like https://github.com/flutter/flutter/issues/21418 which were skipped // over because other integration tests run using flutter-tester which short-cuts // some of the checks for devices. - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); const ProcessManager processManager = LocalProcessManager(); final ProcessResult proc = await processManager.run( diff --git a/packages/flutter_tools/test/integration.shard/flutter_run_with_error_test.dart b/packages/flutter_tools/test/integration.shard/flutter_run_with_error_test.dart index 4088ce96839..b980f1db826 100644 --- a/packages/flutter_tools/test/integration.shard/flutter_run_with_error_test.dart +++ b/packages/flutter_tools/test/integration.shard/flutter_run_with_error_test.dart @@ -31,12 +31,6 @@ void main() { }); testWithoutContext('flutter run in non-machine mode reports an early error in an application', () async { - final String flutterBin = fileSystem.path.join( - getFlutterRoot(), - 'bin', - 'flutter', - ); - final StringBuffer stdout = StringBuffer(); final Process process = await processManager.start([ diff --git a/packages/flutter_tools/test/integration.shard/gradle_non_android_plugin_test.dart b/packages/flutter_tools/test/integration.shard/gradle_non_android_plugin_test.dart index 59899ce826a..c5cc633c8bd 100644 --- a/packages/flutter_tools/test/integration.shard/gradle_non_android_plugin_test.dart +++ b/packages/flutter_tools/test/integration.shard/gradle_non_android_plugin_test.dart @@ -21,12 +21,6 @@ void main() { }); testWithoutContext('Flutter app that depends on a non-Android plugin can still build for Android', () { - final String flutterRoot = getFlutterRoot(); - final String flutterBin = fileSystem.path.join( - flutterRoot, - 'bin', - 'flutter', - ); processManager.runSync([ flutterBin, ...getLocalEngineArguments(), diff --git a/packages/flutter_tools/test/integration.shard/isolated/native_assets_agp_version_test.dart b/packages/flutter_tools/test/integration.shard/isolated/native_assets_agp_version_test.dart index 41acde68397..6973af8c648 100644 --- a/packages/flutter_tools/test/integration.shard/isolated/native_assets_agp_version_test.dart +++ b/packages/flutter_tools/test/integration.shard/isolated/native_assets_agp_version_test.dart @@ -13,7 +13,7 @@ import 'package:file/file.dart'; import 'package:file_testing/file_testing.dart'; import '../../src/common.dart'; -import '../test_utils.dart' show platform; +import '../test_utils.dart' show flutterBin, platform; import '../transition_test_utils.dart'; import 'native_assets_test_utils.dart'; diff --git a/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart b/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart index 572fb2959fb..8d09e2af7db 100644 --- a/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart +++ b/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart @@ -24,7 +24,7 @@ import 'package:flutter_tools/src/base/os.dart'; import 'package:native_assets_cli/code_assets_builder.dart'; import '../../src/common.dart'; -import '../test_utils.dart' show fileSystem, platform; +import '../test_utils.dart' show fileSystem, flutterBin, platform; import '../transition_test_utils.dart'; import 'native_assets_test_utils.dart'; diff --git a/packages/flutter_tools/test/integration.shard/isolated/native_assets_test_utils.dart b/packages/flutter_tools/test/integration.shard/isolated/native_assets_test_utils.dart index 22d81341626..7cac9b11cb4 100644 --- a/packages/flutter_tools/test/integration.shard/isolated/native_assets_test_utils.dart +++ b/packages/flutter_tools/test/integration.shard/isolated/native_assets_test_utils.dart @@ -10,7 +10,7 @@ import 'package:file_testing/file_testing.dart'; import 'package:yaml/yaml.dart'; import '../../src/common.dart'; -import '../test_utils.dart' show ProcessResultMatcher, fileSystem; +import '../test_utils.dart' show ProcessResultMatcher, fileSystem, flutterBin; import '../transition_test_utils.dart'; Future createTestProject(String packageName, Directory tempDirectory) async { diff --git a/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart b/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart index 2e36b4f616e..0b06f436bfa 100644 --- a/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart +++ b/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart @@ -15,7 +15,6 @@ import 'package:yaml/yaml.dart'; import '../../src/common.dart'; import '../test_utils.dart'; -import '../transition_test_utils.dart'; import 'native_assets_test_utils.dart'; /// Regression test as part of https://github.com/flutter/flutter/pull/150742. diff --git a/packages/flutter_tools/test/integration.shard/observatory_port_test.dart b/packages/flutter_tools/test/integration.shard/observatory_port_test.dart index 94e5cf9f434..eb143e2f85b 100644 --- a/packages/flutter_tools/test/integration.shard/observatory_port_test.dart +++ b/packages/flutter_tools/test/integration.shard/observatory_port_test.dart @@ -54,7 +54,6 @@ void main() { }); testWithoutContext('flutter run --vm-service-port', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final int port = await getFreePort(); // If only --vm-service-port is provided, --vm-service-port will be used by DDS // and the VM service will bind to a random port. @@ -72,7 +71,6 @@ void main() { }); testWithoutContext('flutter run --dds-port --vm-service-port', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final int vmServicePort = await getFreePort(); int ddsPort = await getFreePort(); while (ddsPort == vmServicePort) { @@ -95,7 +93,6 @@ void main() { }); testWithoutContext('flutter run --dds-port', () async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); final int ddsPort = await getFreePort(); // If only --dds-port is provided, --dds-port will be used by DDS and the VM service // will bind to a random port. diff --git a/packages/flutter_tools/test/integration.shard/swift_package_manager_create_app_test.dart b/packages/flutter_tools/test/integration.shard/swift_package_manager_create_app_test.dart index f40e0f6de23..4073863650c 100644 --- a/packages/flutter_tools/test/integration.shard/swift_package_manager_create_app_test.dart +++ b/packages/flutter_tools/test/integration.shard/swift_package_manager_create_app_test.dart @@ -10,12 +10,6 @@ import 'swift_package_manager_utils.dart'; import 'test_utils.dart'; void main() { - final String flutterBin = fileSystem.path.join( - getFlutterRoot(), - 'bin', - 'flutter', - ); - final List platforms = ['ios', 'macos']; for (final String platformName in platforms) { final List iosLanguages = [ diff --git a/packages/flutter_tools/test/integration.shard/swift_package_manager_create_plugin_test.dart b/packages/flutter_tools/test/integration.shard/swift_package_manager_create_plugin_test.dart index 64b9761f97e..55c3426adbc 100644 --- a/packages/flutter_tools/test/integration.shard/swift_package_manager_create_plugin_test.dart +++ b/packages/flutter_tools/test/integration.shard/swift_package_manager_create_plugin_test.dart @@ -10,12 +10,6 @@ import 'swift_package_manager_utils.dart'; import 'test_utils.dart'; void main() { - final String flutterBin = fileSystem.path.join( - getFlutterRoot(), - 'bin', - 'flutter', - ); - final List platforms = ['ios', 'macos']; for (final String platformName in platforms) { final List iosLanguages = [ diff --git a/packages/flutter_tools/test/integration.shard/swift_package_manager_test.dart b/packages/flutter_tools/test/integration.shard/swift_package_manager_test.dart index dcc7f09df16..62bd5206175 100644 --- a/packages/flutter_tools/test/integration.shard/swift_package_manager_test.dart +++ b/packages/flutter_tools/test/integration.shard/swift_package_manager_test.dart @@ -13,12 +13,6 @@ import 'swift_package_manager_utils.dart'; import 'test_utils.dart'; void main() { - final String flutterBin = fileSystem.path.join( - getFlutterRoot(), - 'bin', - 'flutter', - ); - final List platforms = ['ios', 'macos']; for (final String platformName in platforms) { final List iosLanguages = [ diff --git a/packages/flutter_tools/test/integration.shard/test_driver.dart b/packages/flutter_tools/test/integration.shard/test_driver.dart index 017a4f99c3c..04941ba2e84 100644 --- a/packages/flutter_tools/test/integration.shard/test_driver.dart +++ b/packages/flutter_tools/test/integration.shard/test_driver.dart @@ -92,7 +92,6 @@ abstract class FlutterTestDriver { bool withDebugger = false, bool verbose = false, }) async { - final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); if (withDebugger) { arguments.add('--start-paused'); } diff --git a/packages/flutter_tools/test/integration.shard/test_test.dart b/packages/flutter_tools/test/integration.shard/test_test.dart index b84248f83e8..eef2cd407ce 100644 --- a/packages/flutter_tools/test/integration.shard/test_test.dart +++ b/packages/flutter_tools/test/integration.shard/test_test.dart @@ -17,7 +17,6 @@ final String automatedTestsDirectory = fileSystem.path.join('..', '..', 'dev', ' final String missingDependencyDirectory = fileSystem.path.join('..', '..', 'dev', 'missing_dependency_tests'); final String flutterTestDirectory = fileSystem.path.join(automatedTestsDirectory, 'flutter_test'); final String integrationTestDirectory = fileSystem.path.join(automatedTestsDirectory, 'integration_test'); -final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', platform.isWindows ? 'flutter.bat' : 'flutter'); // Running Integration Tests in the Flutter Tester will still exercise the same // flows specific to Integration Tests. diff --git a/packages/flutter_tools/test/integration.shard/test_utils.dart b/packages/flutter_tools/test/integration.shard/test_utils.dart index fa505c61213..aa0eeb2a4e6 100644 --- a/packages/flutter_tools/test/integration.shard/test_utils.dart +++ b/packages/flutter_tools/test/integration.shard/test_utils.dart @@ -15,6 +15,13 @@ import 'test_driver.dart'; /// The [FileSystem] for the integration test environment. const FileSystem fileSystem = LocalFileSystem(); +/// The (real) `flutter` binary (i.e. `{ROOT}/bin/flutter`) to execute in tests. +final String flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + platform.isWindows ? 'flutter.bat' : 'flutter', +); + /// The [Platform] for the integration test environment. const Platform platform = LocalPlatform(); diff --git a/packages/flutter_tools/test/integration.shard/transition_test_utils.dart b/packages/flutter_tools/test/integration.shard/transition_test_utils.dart index e0e0c0876b6..0b98b6af7e0 100644 --- a/packages/flutter_tools/test/integration.shard/transition_test_utils.dart +++ b/packages/flutter_tools/test/integration.shard/transition_test_utils.dart @@ -11,11 +11,10 @@ import 'package:meta/meta.dart'; import 'package:process/process.dart'; import '../src/common.dart'; -import 'test_utils.dart' show fileSystem; +import 'test_utils.dart' show flutterBin; const ProcessManager processManager = LocalProcessManager(); final String flutterRoot = getFlutterRoot(); -final String flutterBin = fileSystem.path.join(flutterRoot, 'bin', 'flutter'); void debugPrint(String message) { // This is called to intentionally print debugging output when a test is From 26d5ec3edd32541a8f42631e363a280796094d1b Mon Sep 17 00:00:00 2001 From: Kate Lovett Date: Mon, 18 Nov 2024 11:32:23 -0800 Subject: [PATCH 118/386] Prettier merge_queue.md (#158969) Spruced up a bit, added mention of edge case for older PRs. ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --------- Co-authored-by: David Iglesias --- docs/infra/merge_queue.md | 46 +++++++++++++++++++++++++++++---------- 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/docs/infra/merge_queue.md b/docs/infra/merge_queue.md index dd8bdebf07e..eaf5bbca0ef 100644 --- a/docs/infra/merge_queue.md +++ b/docs/infra/merge_queue.md @@ -2,10 +2,15 @@ If you are not hacking on flutter/flutter, you can stop reading now. -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. +> [!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? -On Friday November 15, 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) @@ -16,19 +21,36 @@ With the merge queue, the button will now look like this: 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. -What's "Remove from queue"? Can I click it? + +--- + +### 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, @jtmcdole, @christopherfujino, @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. +> [!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. -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. +--- + +### 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. From c7d158d9f9f1d71d53822a12caa89822d4008ee5 Mon Sep 17 00:00:00 2001 From: Ben Konyi Date: Mon, 18 Nov 2024 14:52:52 -0500 Subject: [PATCH 119/386] Fix flaky failure related to core_device_list.json not being found (#158946) It's possible that the tool can be 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. Fixes https://github.com/flutter/flutter/issues/141892 --------- Co-authored-by: Andrew Kolos --- .../lib/src/base/file_system.dart | 6 ++ .../lib/src/ios/core_devices.dart | 12 +++- .../general.shard/ios/core_devices_test.dart | 57 +++++++++++++++++++ 3 files changed, 74 insertions(+), 1 deletion(-) 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/ios/core_devices.dart b/packages/flutter_tools/lib/src/ios/core_devices.dart index e7eff51e285..2ccbb21a6a9 100644 --- a/packages/flutter_tools/lib/src/ios/core_devices.dart +++ b/packages/flutter_tools/lib/src/ios/core_devices.dart @@ -79,14 +79,24 @@ class IOSCoreDeviceControl { try { final RunResult result = await _processUtils.run(command, throwOnError: true); + final bool isToolPossiblyShutdown = _fileSystem is LocalFileSystem && _fileSystem.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/test/general.shard/ios/core_devices_test.dart b/packages/flutter_tools/test/general.shard/ios/core_devices_test.dart index 860947c0ca6..1b54f2fa510 100644 --- a/packages/flutter_tools/test/general.shard/ios/core_devices_test.dart +++ b/packages/flutter_tools/test/general.shard/ios/core_devices_test.dart @@ -7,6 +7,7 @@ import 'package:file_testing/file_testing.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/base/signals.dart'; import 'package:flutter_tools/src/base/version.dart'; import 'package:flutter_tools/src/ios/core_devices.dart'; import 'package:flutter_tools/src/ios/xcodeproj.dart'; @@ -15,6 +16,15 @@ import 'package:flutter_tools/src/macos/xcode.dart'; import '../../src/common.dart'; import '../../src/fake_process_manager.dart'; +class LocalFileSystemFake extends LocalFileSystem { + LocalFileSystemFake.test({required super.signals}) : super.test(); + + MemoryFileSystem memoryFileSystem = MemoryFileSystem.test(); + + @override + Directory get systemTempDirectory => memoryFileSystem.systemTempDirectory; +} + void main() { late MemoryFileSystem fileSystem; @@ -1400,6 +1410,53 @@ invalid JSON expect(fakeProcessManager, hasNoRemainingExpectations); }); + testWithoutContext('Handles file system disposal', () async { + final LocalFileSystem localFs = LocalFileSystemFake.test(signals: Signals.test()); + deviceControl = IOSCoreDeviceControl( + logger: logger, + processManager: fakeProcessManager, + xcode: xcode, + fileSystem: localFs, + ); + final Directory tempDir = localFs.systemTempDirectory + .childDirectory('core_devices.rand0'); + final File tempFile = tempDir.childFile('core_device_list.json'); + final List args = [ + 'xcrun', + 'devicectl', + 'list', + 'devices', + '--timeout', + '5', + '--json-output', + tempFile.path, + ]; + fakeProcessManager.addCommand(FakeCommand( + command: args, + onRun: (_) { + // Simulate that the tool started shutting down and disposed the + // file system, causing the temp directory to be deleted before + // this program invocation returns a result. + localFs.dispose(); + expect(localFs.disposed, true); + }, + )); + + final List coreDevices = await deviceControl.getCoreDevices(); + expect(coreDevices, isEmpty); + expect( + logger.errorText, + isNot( + contains('After running the command xcrun devicectl list devices ' + '--timeout 5 --json-output ${tempFile.path} the file\n' + '${tempFile.path} was expected to exist, but it did not', + ), + ), + ); + expect(fakeProcessManager, hasNoRemainingExpectations); + }); + + testWithoutContext('No devices', () async { const String deviceControlOutput = ''' { From ff47d63235cb60ee52dee6b81041cee0c2bdb944 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Mon, 18 Nov 2024 16:19:04 -0500 Subject: [PATCH 120/386] Roll Flutter Engine from 9686de154114 to 878f593802e1 (5 revisions) (#159097) https://github.com/flutter/engine/compare/9686de154114...878f593802e1 2024-11-18 chris@bracken.jp EmbedderTest: Extract backend-specific user_data (flutter/engine#56642) 2024-11-18 skia-flutter-autoroll@skia.org Roll Dart SDK from ae5111067032 to 625e0a9cb67a (1 revision) (flutter/engine#56679) 2024-11-18 30870216+gaaclarke@users.noreply.github.com Started only loading gles3 functions if we have a gles3 context (flutter/engine#56636) 2024-11-18 30870216+gaaclarke@users.noreply.github.com [impeller] enable framebuffer blit when available (flutter/engine#56596) 2024-11-18 skia-flutter-autoroll@skia.org Roll Skia from 7594233ff914 to 0b74d5c3eb4f (4 revisions) (flutter/engine#56678) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index ef56311a2ba..ead9c298863 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -9686de154114bc3f487aec34ba0a4f6a8a6358ef +878f593802e16bbbc7fd7ff86c24a40302095e48 From c25790e3db919682e3afb784eee4a6300ddfdffa Mon Sep 17 00:00:00 2001 From: Nate Wilson Date: Mon, 18 Nov 2024 14:28:08 -0700 Subject: [PATCH 121/386] Add `@protected` to public `State` method overrides (#157313) I don't want to see these methods in my autofill suggestions.
![navigator dispose](https://github.com/user-attachments/assets/5d2dc37c-abe9-44f4-ad16-4396a3aeeaf7) --- dev/bots/analyze.dart | 8 +- .../protect_public_state_subtypes.dart | 101 ++++++++++++++++++ packages/flutter/lib/src/material/drawer.dart | 5 + .../src/material/paginated_data_table.dart | 5 + .../flutter/lib/src/material/popup_menu.dart | 2 + .../lib/src/material/refresh_indicator.dart | 5 + .../flutter/lib/src/material/scaffold.dart | 9 ++ .../lib/src/material/segmented_button.dart | 3 + .../lib/src/material/selection_area.dart | 1 + .../flutter/lib/src/material/tooltip.dart | 4 + .../lib/src/widgets/animated_scroll_view.dart | 8 +- .../flutter/lib/src/widgets/autofill.dart | 3 + .../lib/src/widgets/editable_text.dart | 5 + packages/flutter/lib/src/widgets/form.dart | 7 ++ .../flutter/lib/src/widgets/framework.dart | 3 + .../lib/src/widgets/gesture_detector.dart | 5 + .../lib/src/widgets/implicit_animations.dart | 4 + .../flutter/lib/src/widgets/navigator.dart | 9 ++ .../lib/src/widgets/nested_scroll_view.dart | 5 + packages/flutter/lib/src/widgets/overlay.dart | 3 + .../lib/src/widgets/reorderable_list.dart | 5 + .../widgets/scroll_notification_observer.dart | 2 + .../flutter/lib/src/widgets/scrollable.dart | 12 +++ .../flutter/lib/src/widgets/scrollbar.dart | 5 + .../lib/src/widgets/selectable_region.dart | 5 + .../flutter/lib/src/widgets/undo_history.dart | 4 + 26 files changed, 223 insertions(+), 5 deletions(-) create mode 100644 dev/bots/custom_rules/protect_public_state_subtypes.dart diff --git a/dev/bots/analyze.dart b/dev/bots/analyze.dart index 49a4e1f0fa1..7102ecb51ff 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, 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/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/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 fc13494539a..1aef889e31f 100644 --- a/packages/flutter/lib/src/material/popup_menu.dart +++ b/packages/flutter/lib/src/material/popup_menu.dart @@ -356,6 +356,7 @@ class PopupMenuItemState> extends State { widget.onTap?.call(); } + @protected @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); @@ -1544,6 +1545,7 @@ class PopupMenuButtonState extends State> { }; } + @protected @override Widget build(BuildContext context) { final IconThemeData iconTheme = IconTheme.of(context); 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/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/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/selection_area.dart b/packages/flutter/lib/src/material/selection_area.dart index be1a26aa2e5..41c949032b5 100644 --- a/packages/flutter/lib/src/material/selection_area.dart +++ b/packages/flutter/lib/src/material/selection_area.dart @@ -113,6 +113,7 @@ class SelectionAreaState extends State { /// The [State] of the [SelectableRegion] for which this [SelectionArea] wraps. SelectableRegionState get selectableRegion => _selectableRegionKey.currentState!; + @protected @override Widget build(BuildContext context) { assert(debugCheckHasMaterialLocalizations(context)); diff --git a/packages/flutter/lib/src/material/tooltip.dart b/packages/flutter/lib/src/material/tooltip.dart index d994d37af34..1258e285f3e 100644 --- a/packages/flutter/lib/src/material/tooltip.dart +++ b/packages/flutter/lib/src/material/tooltip.dart @@ -706,6 +706,7 @@ class TooltipState extends State with SingleTickerProviderStateMixin { return true; } + @protected @override void initState() { super.initState(); @@ -715,6 +716,7 @@ class TooltipState extends State with SingleTickerProviderStateMixin { GestureBinding.instance.pointerRouter.addGlobalRoute(_handleGlobalPointerEvent); } + @protected @override void didChangeDependencies() { super.didChangeDependencies(); @@ -797,6 +799,7 @@ class TooltipState extends State with SingleTickerProviderStateMixin { : SelectionContainer.disabled(child: overlayChild); } + @protected @override void dispose() { GestureBinding.instance.pointerRouter.removeGlobalRoute(_handleGlobalPointerEvent); @@ -815,6 +818,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 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/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/editable_text.dart b/packages/flutter/lib/src/widgets/editable_text.dart index 9ae6d0f6004..6e1a11f01ed 100644 --- a/packages/flutter/lib/src/widgets/editable_text.dart +++ b/packages/flutter/lib/src/widgets/editable_text.dart @@ -2979,6 +2979,7 @@ class EditableTextState extends State with AutomaticKeepAliveClien // State lifecycle: + @protected @override void initState() { super.initState(); @@ -3005,6 +3006,7 @@ class EditableTextState extends State with AutomaticKeepAliveClien // cursor) are supposed to run. bool _tickersEnabled = true; + @protected @override void didChangeDependencies() { super.didChangeDependencies(); @@ -3080,6 +3082,7 @@ class EditableTextState extends State with AutomaticKeepAliveClien } } + @protected @override void didUpdateWidget(EditableText oldWidget) { super.didUpdateWidget(oldWidget); @@ -3183,6 +3186,7 @@ class EditableTextState extends State with AutomaticKeepAliveClien } } + @protected @override void dispose() { _internalScrollController?.dispose(); @@ -5178,6 +5182,7 @@ class EditableTextState extends State with AutomaticKeepAliveClien EditableTextTapOutsideIntent: _makeOverridable(_EditableTextTapOutsideAction()), }; + @protected @override Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); diff --git a/packages/flutter/lib/src/widgets/form.dart b/packages/flutter/lib/src/widgets/form.dart index 525cd02b544..7be29d6eaa4 100644 --- a/packages/flutter/lib/src/widgets/form.dart +++ b/packages/flutter/lib/src/widgets/form.dart @@ -268,6 +268,7 @@ class FormState extends State
{ } } + @protected @override Widget build(BuildContext context) { switch (widget.autovalidateMode) { @@ -671,24 +672,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 +702,7 @@ class FormFieldState extends State> with RestorationMixin { } } + @protected @override void dispose() { _errorText.dispose(); @@ -705,6 +711,7 @@ class FormFieldState extends State> with RestorationMixin { super.dispose(); } + @protected @override Widget build(BuildContext context) { if (widget.enabled) { diff --git a/packages/flutter/lib/src/widgets/framework.dart b/packages/flutter/lib/src/widgets/framework.dart index d62671075c2..e0d5d9377f4 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 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/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/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..ef41d895869 100644 --- a/packages/flutter/lib/src/widgets/nested_scroll_view.dart +++ b/packages/flutter/lib/src/widgets/nested_scroll_view.dart @@ -425,6 +425,7 @@ class NestedScrollViewState extends State { _NestedScrollCoordinator? _coordinator; + @protected @override void initState() { super.initState(); @@ -436,12 +437,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 +453,7 @@ class NestedScrollViewState extends State { } } + @protected @override void dispose() { _coordinator!.dispose(); @@ -476,6 +480,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/reorderable_list.dart b/packages/flutter/lib/src/widgets/reorderable_list.dart index 1900b3ad573..96ea0c0bc96 100644 --- a/packages/flutter/lib/src/widgets/reorderable_list.dart +++ b/packages/flutter/lib/src/widgets/reorderable_list.dart @@ -388,6 +388,7 @@ class ReorderableListState extends State { _sliverReorderableListKey.currentState!.cancelReorder(); } + @protected @override Widget build(BuildContext context) { return CustomScrollView( @@ -630,6 +631,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 +646,7 @@ class SliverReorderableListState extends State with Ticke } } + @protected @override void didUpdateWidget(covariant SliverReorderableList oldWidget) { super.didUpdateWidget(oldWidget); @@ -661,6 +664,7 @@ class SliverReorderableListState extends State with Ticke } } + @protected @override void dispose() { _dragReset(); @@ -1030,6 +1034,7 @@ class SliverReorderableListState extends State with Ticke ); } + @protected @override Widget build(BuildContext context) { assert(debugCheckHasOverlay(context)); 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/scrollable.dart b/packages/flutter/lib/src/widgets/scrollable.dart index 57b55cb8fd7..976c025c393 100644 --- a/packages/flutter/lib/src/widgets/scrollable.dart +++ b/packages/flutter/lib/src/widgets/scrollable.dart @@ -626,6 +626,7 @@ class ScrollableState extends State with TickerProviderStateMixin, R _effectiveScrollController.attach(position); } + @protected @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(_persistedScrollOffset, 'offset'); @@ -635,6 +636,7 @@ class ScrollableState extends State with TickerProviderStateMixin, R } } + @protected @override void saveOffset(double offset) { assert(debugIsSerializableForRestoration(offset)); @@ -644,6 +646,7 @@ class ScrollableState extends State with TickerProviderStateMixin, R ServicesBinding.instance.restorationManager.flushData(); } + @protected @override void initState() { if (widget.controller == null) { @@ -652,6 +655,7 @@ class ScrollableState extends State with TickerProviderStateMixin, R super.initState(); } + @protected @override void didChangeDependencies() { _mediaQueryGestureSettings = MediaQuery.maybeGestureSettingsOf(context); @@ -680,6 +684,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 +716,7 @@ class ScrollableState extends State with TickerProviderStateMixin, R } } + @protected @override void dispose() { if (widget.controller != null) { @@ -980,6 +986,7 @@ class ScrollableState extends State with TickerProviderStateMixin, R // DESCRIPTION + @protected @override Widget build(BuildContext context) { assert(_position != null); @@ -1064,6 +1071,7 @@ class ScrollableState extends State with TickerProviderStateMixin, R return (>[ ensureVisibleFuture ], this); } + @protected @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); @@ -1934,6 +1942,7 @@ class TwoDimensionalScrollableState extends State { return _horizontalInnerScrollableKey.currentState!; } + @protected @override void initState() { if (widget.verticalDetails.controller == null) { @@ -1945,6 +1954,7 @@ class TwoDimensionalScrollableState extends State { super.initState(); } + @protected @override void didUpdateWidget(TwoDimensionalScrollable oldWidget) { super.didUpdateWidget(oldWidget); @@ -1985,6 +1995,7 @@ class TwoDimensionalScrollableState extends State { } } + @protected @override Widget build(BuildContext context) { assert( @@ -2049,6 +2060,7 @@ class TwoDimensionalScrollableState extends State { ); } + @protected @override void dispose() { _verticalFallbackController?.dispose(); 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 dace673d580..430eb316744 100644 --- a/packages/flutter/lib/src/widgets/selectable_region.dart +++ b/packages/flutter/lib/src/widgets/selectable_region.dart @@ -375,6 +375,7 @@ class SelectableRegionState extends State with TextSelectionDe FocusNode? _localFocusNode; FocusNode get _focusNode => widget.focusNode ?? (_localFocusNode ??= FocusNode(debugLabel: 'SelectableRegion')); + @protected @override void initState() { super.initState(); @@ -398,6 +399,7 @@ class SelectableRegionState extends State with TextSelectionDe _processTextActions.addAll(await _processTextService.queryTextActions()); } + @protected @override void didChangeDependencies() { super.didChangeDependencies(); @@ -424,6 +426,7 @@ class SelectableRegionState extends State with TextSelectionDe } } + @protected @override void didUpdateWidget(SelectableRegion oldWidget) { super.didUpdateWidget(oldWidget); @@ -1704,6 +1707,7 @@ class SelectableRegionState extends State with TextSelectionDe _selectable = null; } + @protected @override void dispose() { _selectable?.removeListener(_updateSelectionStatus); @@ -1720,6 +1724,7 @@ class SelectableRegionState extends State with TextSelectionDe super.dispose(); } + @protected @override Widget build(BuildContext context) { assert(debugCheckHasOverlay(context)); 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( From 7d4b2d31fcd58f030d855e37b76ccb6e04be2cef Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 18 Nov 2024 22:28:05 +0000 Subject: [PATCH 122/386] Bump codecov/codecov-action from 4.6.0 to 5.0.2 in the all-github-actions group (#159104) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps the all-github-actions group with 1 update: [codecov/codecov-action](https://github.com/codecov/codecov-action). Updates `codecov/codecov-action` from 4.6.0 to 5.0.2
Release notes

Sourced from codecov/codecov-action's releases.

v5.0.2

What's Changed

Full Changelog: https://github.com/codecov/codecov-action/compare/v5.0.1...v5.0.2

v5.0.1

What's Changed

Full Changelog: https://github.com/codecov/codecov-action/compare/v5.0.0...v5.0.1

v5.0.0

v5 Release

v5 of the Codecov GitHub Action will use the Codecov Wrapper to encapsulate the CLI. This will help ensure that the Action gets updates quicker.

Migration Guide

The v5 release also coincides with the opt-out feature for tokens for public repositories. In the Global Upload Token section of the settings page of an organization in codecov.io, you can set the ability for Codecov to receive a coverage reports from any source. This will allow contributors or other members of a repository to upload without needing access to the Codecov token. For more details see how to upload without a token.

[!WARNING]
The following arguments have been changed

  • file (this has been deprecated in favor of files)
  • plugin (this has been deprecated in favor of plugins)

The following arguments have been added:

  • binary
  • gcov_args
  • gcov_executable
  • gcov_ignore
  • gcov_include
  • report_type
  • skip_validation
  • swift_project

You can see their usage in the action.yml file.

What's Changed

... (truncated)

Commits

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=codecov/codecov-action&package-manager=github_actions&previous-version=4.6.0&new-version=5.0.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) - `@dependabot ignore minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) - `@dependabot ignore ` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) - `@dependabot unignore ` will remove all of the ignore conditions of the specified dependency - `@dependabot unignore ` will remove the ignore condition of the specified dependency and ignore conditions
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/coverage.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 319db1980a0..4f0b66cb382 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -23,7 +23,7 @@ jobs: - 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@5c47607acb93fed5485fdbf7232e8a31425f672a with: files: packages/flutter/coverage/lcov.info verbose: true From 3a17b6735358e48a73c1e65c33436b2fcc1ca6a2 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Mon, 18 Nov 2024 15:37:05 -0800 Subject: [PATCH 123/386] Add a tag and assert some state in FlutterTestDriver tests. (#159099) Towards https://github.com/flutter/flutter/issues/51421. Asserts some state we would not like to be hit by in integration tests using `Flutter*TestDriver`. In addition, adds a tag that can be used to run all tests that currently use this pattern: ```sh flutter test --tags flutter-test-driver ``` This showcases processes leaking quite a bit: . --- packages/flutter_tools/dart_test.yaml | 6 ++++ .../background_isolate_test.dart | 3 ++ .../break_on_framework_exceptions_test.dart | 3 ++ .../coverage_collection_test.dart | 3 ++ .../debugger_stepping_test.dart | 3 ++ .../deferred_components_test.dart | 3 ++ .../flutter_attach_test.dart | 3 ++ .../integration.shard/flutter_gen_test.dart | 3 ++ .../integration.shard/flutter_run_test.dart | 3 ++ .../flutter_run_with_error_test.dart | 3 ++ .../test/integration.shard/gen_l10n_test.dart | 3 ++ .../hot_reload_errors_test.dart | 3 ++ .../integration.shard/hot_reload_test.dart | 3 ++ .../hot_reload_with_asset_test.dart | 3 ++ .../test/integration.shard/lifetime_test.dart | 3 ++ .../stateless_stateful_hot_reload_test.dart | 3 ++ .../test/integration.shard/test_driver.dart | 33 ++++++++++++++++--- .../test/integration.shard/timeline_test.dart | 3 ++ .../vmservice_integration_test.dart | 3 ++ .../web.shard/debugger_stepping_web_test.dart | 3 ++ .../expression_evaluation_web_test.dart | 3 ++ .../test/web.shard/hot_reload_web_test.dart | 3 ++ .../test/web.shard/output_web_test.dart | 3 ++ .../test/web.shard/vm_service_web_test.dart | 3 ++ .../test/web.shard/web_run_test.dart | 3 ++ 25 files changed, 104 insertions(+), 4 deletions(-) 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/test/integration.shard/background_isolate_test.dart b/packages/flutter_tools/test/integration.shard/background_isolate_test.dart index eef89db5fc3..aa92825a2db 100644 --- a/packages/flutter_tools/test/integration.shard/background_isolate_test.dart +++ b/packages/flutter_tools/test/integration.shard/background_isolate_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'dart:async'; import 'package:file/file.dart'; diff --git a/packages/flutter_tools/test/integration.shard/break_on_framework_exceptions_test.dart b/packages/flutter_tools/test/integration.shard/break_on_framework_exceptions_test.dart index 8599d6230f6..dd699b5a463 100644 --- a/packages/flutter_tools/test/integration.shard/break_on_framework_exceptions_test.dart +++ b/packages/flutter_tools/test/integration.shard/break_on_framework_exceptions_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'dart:async'; import 'package:file/file.dart'; diff --git a/packages/flutter_tools/test/integration.shard/coverage_collection_test.dart b/packages/flutter_tools/test/integration.shard/coverage_collection_test.dart index 22a52a3a010..e14a5a2a479 100644 --- a/packages/flutter_tools/test/integration.shard/coverage_collection_test.dart +++ b/packages/flutter_tools/test/integration.shard/coverage_collection_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'package:file/file.dart'; import 'package:file_testing/file_testing.dart'; diff --git a/packages/flutter_tools/test/integration.shard/debugger_stepping_test.dart b/packages/flutter_tools/test/integration.shard/debugger_stepping_test.dart index 652ca848754..09ef630e471 100644 --- a/packages/flutter_tools/test/integration.shard/debugger_stepping_test.dart +++ b/packages/flutter_tools/test/integration.shard/debugger_stepping_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'package:file/file.dart'; import '../src/common.dart'; diff --git a/packages/flutter_tools/test/integration.shard/deferred_components_test.dart b/packages/flutter_tools/test/integration.shard/deferred_components_test.dart index 0402e8d4d7c..8f82cab0788 100644 --- a/packages/flutter_tools/test/integration.shard/deferred_components_test.dart +++ b/packages/flutter_tools/test/integration.shard/deferred_components_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'package:archive/archive.dart'; import 'package:file/file.dart'; import 'package:file_testing/file_testing.dart'; diff --git a/packages/flutter_tools/test/integration.shard/flutter_attach_test.dart b/packages/flutter_tools/test/integration.shard/flutter_attach_test.dart index 1d92a7a4b7c..079b4908d00 100644 --- a/packages/flutter_tools/test/integration.shard/flutter_attach_test.dart +++ b/packages/flutter_tools/test/integration.shard/flutter_attach_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'dart:convert'; import 'package:file/file.dart'; diff --git a/packages/flutter_tools/test/integration.shard/flutter_gen_test.dart b/packages/flutter_tools/test/integration.shard/flutter_gen_test.dart index 674d5a1c584..c9e9490089d 100644 --- a/packages/flutter_tools/test/integration.shard/flutter_gen_test.dart +++ b/packages/flutter_tools/test/integration.shard/flutter_gen_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'dart:convert'; import 'package:file/file.dart'; diff --git a/packages/flutter_tools/test/integration.shard/flutter_run_test.dart b/packages/flutter_tools/test/integration.shard/flutter_run_test.dart index bff3bae35cb..345e3bdd801 100644 --- a/packages/flutter_tools/test/integration.shard/flutter_run_test.dart +++ b/packages/flutter_tools/test/integration.shard/flutter_run_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'package:file/file.dart'; import 'package:flutter_tools/src/base/io.dart'; import 'package:process/process.dart'; diff --git a/packages/flutter_tools/test/integration.shard/flutter_run_with_error_test.dart b/packages/flutter_tools/test/integration.shard/flutter_run_with_error_test.dart index b980f1db826..84281150cb5 100644 --- a/packages/flutter_tools/test/integration.shard/flutter_run_with_error_test.dart +++ b/packages/flutter_tools/test/integration.shard/flutter_run_with_error_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'dart:async'; import 'package:file/file.dart'; diff --git a/packages/flutter_tools/test/integration.shard/gen_l10n_test.dart b/packages/flutter_tools/test/integration.shard/gen_l10n_test.dart index 268ec5e0249..3567844e3d6 100644 --- a/packages/flutter_tools/test/integration.shard/gen_l10n_test.dart +++ b/packages/flutter_tools/test/integration.shard/gen_l10n_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'dart:async'; import 'package:file/file.dart'; diff --git a/packages/flutter_tools/test/integration.shard/hot_reload_errors_test.dart b/packages/flutter_tools/test/integration.shard/hot_reload_errors_test.dart index edddb6864b9..966d2b558ae 100644 --- a/packages/flutter_tools/test/integration.shard/hot_reload_errors_test.dart +++ b/packages/flutter_tools/test/integration.shard/hot_reload_errors_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'package:file/file.dart'; import '../src/common.dart'; diff --git a/packages/flutter_tools/test/integration.shard/hot_reload_test.dart b/packages/flutter_tools/test/integration.shard/hot_reload_test.dart index ca2d13b7fc5..7a83d96208d 100644 --- a/packages/flutter_tools/test/integration.shard/hot_reload_test.dart +++ b/packages/flutter_tools/test/integration.shard/hot_reload_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'dart:async'; import 'package:file/file.dart'; diff --git a/packages/flutter_tools/test/integration.shard/hot_reload_with_asset_test.dart b/packages/flutter_tools/test/integration.shard/hot_reload_with_asset_test.dart index 4de27d074f6..aca0f0e41b7 100644 --- a/packages/flutter_tools/test/integration.shard/hot_reload_with_asset_test.dart +++ b/packages/flutter_tools/test/integration.shard/hot_reload_with_asset_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'dart:async'; import 'package:file/file.dart'; diff --git a/packages/flutter_tools/test/integration.shard/lifetime_test.dart b/packages/flutter_tools/test/integration.shard/lifetime_test.dart index bab2ee3e9fa..82a592a2b17 100644 --- a/packages/flutter_tools/test/integration.shard/lifetime_test.dart +++ b/packages/flutter_tools/test/integration.shard/lifetime_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'package:file/file.dart'; import '../src/common.dart'; diff --git a/packages/flutter_tools/test/integration.shard/stateless_stateful_hot_reload_test.dart b/packages/flutter_tools/test/integration.shard/stateless_stateful_hot_reload_test.dart index 21f911d1925..5b7de6ad32d 100644 --- a/packages/flutter_tools/test/integration.shard/stateless_stateful_hot_reload_test.dart +++ b/packages/flutter_tools/test/integration.shard/stateless_stateful_hot_reload_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'dart:async'; import 'package:file/file.dart'; diff --git a/packages/flutter_tools/test/integration.shard/test_driver.dart b/packages/flutter_tools/test/integration.shard/test_driver.dart index 04941ba2e84..810680751f8 100644 --- a/packages/flutter_tools/test/integration.shard/test_driver.dart +++ b/packages/flutter_tools/test/integration.shard/test_driver.dart @@ -10,6 +10,7 @@ import 'package:file/file.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/utils.dart'; +import 'package:meta/meta.dart'; import 'package:process/process.dart'; import 'package:vm_service/vm_service.dart'; import 'package:vm_service/vm_service_io.dart'; @@ -35,7 +36,7 @@ const Duration defaultTimeout = Duration(seconds: 5); const Duration appStartTimeout = Duration(seconds: 120); const Duration quitTimeout = Duration(seconds: 10); -abstract class FlutterTestDriver { +abstract final class FlutterTestDriver { FlutterTestDriver( this._projectFolder, { String? logPrefix, @@ -86,12 +87,17 @@ abstract class FlutterTestDriver { } } + @mustCallSuper Future _setupProcess( List arguments, { String? script, bool withDebugger = false, bool verbose = false, }) async { + if (_process != null && !_hasExited) { + throw StateError('Cannot start another process while the previous runs'); + } + if (withDebugger) { arguments.add('--start-paused'); } @@ -120,6 +126,9 @@ abstract class FlutterTestDriver { // via a getter for external uses. unawaited(_process!.exitCode.then((int code) { _debugPrint('Process exited ($code)'); + // The timing of this signal is important to the implementation of the + // "quit" method, so only change how this is implemented by careful + // testing of tests that use FlutterTestDriver. _hasExited = true; })); transformToLines(_process!.stdout).listen(_stdout.add); @@ -183,8 +192,24 @@ abstract class FlutterTestDriver { ); } - Future quit() => _killGracefully(); + /// Quits the currently running process. + @nonVirtual + Future quit() async { + final int result = await _killGracefully(); + if (result != 0) { + _debugPrint('Expected process to terminate gracefully, got exit code $result.'); + } + // The _hasExited signal could be on the microtask queue. Waiting for a + // Future(...) queues an event similar to Timer.run(Duration.zero), which + // guarantees the current queue has elapsed before moving on. + await Future(() {}); + if (!_hasExited) { + throw StateError('Process did not exit'); + } + } + + @nonVirtual Future _killGracefully() async { if (_processPid == null) { return -1; @@ -484,7 +509,7 @@ abstract class FlutterTestDriver { } } -class FlutterRunTestDriver extends FlutterTestDriver { +final class FlutterRunTestDriver extends FlutterTestDriver { FlutterRunTestDriver( super.projectFolder, { super.logPrefix, @@ -770,7 +795,7 @@ class FlutterRunTestDriver extends FlutterTestDriver { final bool spawnDdsInstance; } -class FlutterTestTestDriver extends FlutterTestDriver { +final class FlutterTestTestDriver extends FlutterTestDriver { FlutterTestTestDriver(super.projectFolder, {super.logPrefix}); Future test({ diff --git a/packages/flutter_tools/test/integration.shard/timeline_test.dart b/packages/flutter_tools/test/integration.shard/timeline_test.dart index d2344c00bb4..61ba301b792 100644 --- a/packages/flutter_tools/test/integration.shard/timeline_test.dart +++ b/packages/flutter_tools/test/integration.shard/timeline_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'dart:async'; import 'package:file/file.dart'; diff --git a/packages/flutter_tools/test/integration.shard/vmservice_integration_test.dart b/packages/flutter_tools/test/integration.shard/vmservice_integration_test.dart index ab66ed3d46c..0defcf44cee 100644 --- a/packages/flutter_tools/test/integration.shard/vmservice_integration_test.dart +++ b/packages/flutter_tools/test/integration.shard/vmservice_integration_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'package:file/file.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:vm_service/vm_service.dart'; diff --git a/packages/flutter_tools/test/web.shard/debugger_stepping_web_test.dart b/packages/flutter_tools/test/web.shard/debugger_stepping_web_test.dart index 0663bb6da38..6631eae8257 100644 --- a/packages/flutter_tools/test/web.shard/debugger_stepping_web_test.dart +++ b/packages/flutter_tools/test/web.shard/debugger_stepping_web_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'package:file/file.dart'; import '../integration.shard/test_data/stepping_project.dart'; diff --git a/packages/flutter_tools/test/web.shard/expression_evaluation_web_test.dart b/packages/flutter_tools/test/web.shard/expression_evaluation_web_test.dart index 737f5e7d4d8..de8283a4acf 100644 --- a/packages/flutter_tools/test/web.shard/expression_evaluation_web_test.dart +++ b/packages/flutter_tools/test/web.shard/expression_evaluation_web_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'package:file/file.dart'; import 'package:vm_service/vm_service.dart'; diff --git a/packages/flutter_tools/test/web.shard/hot_reload_web_test.dart b/packages/flutter_tools/test/web.shard/hot_reload_web_test.dart index 6999255b023..7648634299d 100644 --- a/packages/flutter_tools/test/web.shard/hot_reload_web_test.dart +++ b/packages/flutter_tools/test/web.shard/hot_reload_web_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'dart:async'; import 'package:file/file.dart'; diff --git a/packages/flutter_tools/test/web.shard/output_web_test.dart b/packages/flutter_tools/test/web.shard/output_web_test.dart index 65dd60f9e5e..a820eb1dd73 100644 --- a/packages/flutter_tools/test/web.shard/output_web_test.dart +++ b/packages/flutter_tools/test/web.shard/output_web_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'package:file/file.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:vm_service/vm_service.dart'; diff --git a/packages/flutter_tools/test/web.shard/vm_service_web_test.dart b/packages/flutter_tools/test/web.shard/vm_service_web_test.dart index 5dd5a0bde45..d13ec6f4041 100644 --- a/packages/flutter_tools/test/web.shard/vm_service_web_test.dart +++ b/packages/flutter_tools/test/web.shard/vm_service_web_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'dart:async'; import 'package:file/file.dart'; diff --git a/packages/flutter_tools/test/web.shard/web_run_test.dart b/packages/flutter_tools/test/web.shard/web_run_test.dart index c9c8227051d..82a82242e2e 100644 --- a/packages/flutter_tools/test/web.shard/web_run_test.dart +++ b/packages/flutter_tools/test/web.shard/web_run_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(['flutter-test-driver']) +library; + import 'package:file/file.dart'; import 'package:flutter_tools/src/base/file_system.dart'; From e68ed3d1f1b5233489a6a417776b61d4c6df15c4 Mon Sep 17 00:00:00 2001 From: Greg Spencer Date: Mon, 18 Nov 2024 15:59:28 -0800 Subject: [PATCH 124/386] Plumbs `scrollBehavior` into `SelectableText` so that the scrollbar may be hidden (#158887) ## Description This adds a `scrollBehavior` attribute to `SelectableText` so that the scrolling can be controlled more directly. I added this specifically because it's not possible to turn off the scrollbar on a selectable text, even if you set the scroll physics to be `NeverScrollableScrollPhysics`. We had a UI where we needed to have a clipped, multi-line selectable text field, but have it not be scrollable unless it was expanded in size, and it wasn't possible to hide the scrollbar, but still wanted it to be selectable. ## Tests - Added a test that makes sure that the scroll behavior makes it down to the `Scrollable` in the `EditableText`. --- .../lib/src/material/selectable_text.dart | 7 ++++ .../lib/src/widgets/editable_text.dart | 4 +-- .../src/widgets/list_wheel_scroll_view.dart | 7 +--- .../lib/src/widgets/nested_scroll_view.dart | 7 +--- .../flutter/lib/src/widgets/page_view.dart | 7 +--- .../flutter/lib/src/widgets/scroll_view.dart | 7 +--- .../flutter/lib/src/widgets/scrollable.dart | 7 +++- .../test/widgets/selectable_text_test.dart | 32 +++++++++++++++++++ 8 files changed, 51 insertions(+), 27 deletions(-) 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/widgets/editable_text.dart b/packages/flutter/lib/src/widgets/editable_text.dart index 6e1a11f01ed..a9f88c1dbba 100644 --- a/packages/flutter/lib/src/widgets/editable_text.dart +++ b/packages/flutter/lib/src/widgets/editable_text.dart @@ -1847,17 +1847,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 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/nested_scroll_view.dart b/packages/flutter/lib/src/widgets/nested_scroll_view.dart index ef41d895869..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 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/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 976c025c393..bd00ea99cd7 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} diff --git a/packages/flutter/test/widgets/selectable_text_test.dart b/packages/flutter/test/widgets/selectable_text_test.dart index f9bf5c08f16..89830532b6e 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 { @@ -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', ]); }); From 6b6f481f194453578b286d0fe3ddf8089c202e44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Sharma?= <737941+loic-sharma@users.noreply.github.com> Date: Mon, 18 Nov 2024 17:23:08 -0800 Subject: [PATCH 125/386] [SwiftPM] Move where the migration checks feature flags (#159110) Previously, the Swift Package Manager app migration would only be registered if the feature was on. Now, the Swift Package Manager app migration is always registered but only runs if the SwiftPM feature is on. This change will make it easier to introduce a separate feature flag for just the SwiftPM app migration. This is a refactoring with no semantic change. Part of https://github.com/flutter/flutter/issues/151567 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- packages/flutter_tools/lib/src/ios/mac.dart | 23 ++-- .../lib/src/macos/build_macos.dart | 23 ++-- ...package_manager_integration_migration.dart | 21 +++ ...ge_manager_integration_migration_test.dart | 126 +++++++++++++++++- 4 files changed, 170 insertions(+), 23 deletions(-) diff --git a/packages/flutter_tools/lib/src/ios/mac.dart b/packages/flutter_tools/lib/src/ios/mac.dart index e634f8dc20a..337afd07dff 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; @@ -166,17 +167,17 @@ Future buildXcodeProject({ RemoveBitcodeMigration(app.project, globals.logger), XcodeThinBinaryBuildPhaseInputPathsMigration(app.project, globals.logger), UIApplicationMainDeprecationMigration(app.project, globals.logger), - if (app.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), ]; final ProjectMigration migration = ProjectMigration(migrators); diff --git a/packages/flutter_tools/lib/src/macos/build_macos.dart b/packages/flutter_tools/lib/src/macos/build_macos.dart index f268a928cc4..fe78b29af3f 100644 --- a/packages/flutter_tools/lib/src/macos/build_macos.dart +++ b/packages/flutter_tools/lib/src/macos/build_macos.dart @@ -13,6 +13,7 @@ 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/xcode_build_settings.dart'; import '../ios/xcodeproj.dart'; @@ -91,17 +92,17 @@ Future buildMacOS({ FlutterApplicationMigration(flutterProject.macos, globals.logger), NSApplicationMainDeprecationMigration(flutterProject.macos, globals.logger), SecureRestorableStateMigration(flutterProject.macos, globals.logger), - if (flutterProject.macos.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), ]; final ProjectMigration migration = ProjectMigration(migrators); 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..8e3942ea931 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,6 +45,7 @@ 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'; @@ -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 { diff --git a/packages/flutter_tools/test/general.shard/migrations/swift_package_manager_integration_migration_test.dart b/packages/flutter_tools/test/general.shard/migrations/swift_package_manager_integration_migration_test.dart index 74f60ec85d8..ed602c4451e 100644 --- a/packages/flutter_tools/test/general.shard/migrations/swift_package_manager_integration_migration_test.dart +++ b/packages/flutter_tools/test/general.shard/migrations/swift_package_manager_integration_migration_test.dart @@ -15,6 +15,7 @@ import 'package:flutter_tools/src/project.dart'; import 'package:test/fake.dart'; import '../../src/common.dart'; +import '../../src/fakes.dart'; const List supportedPlatforms = [ SupportedPlatform.ios, @@ -22,8 +23,12 @@ const List supportedPlatforms = [ ]; void main() { + final TestFeatureFlags swiftPackageManagerFullyEnabledFlags = TestFeatureFlags( + isSwiftPackageManagerEnabled: true, + ); + group('Flutter Package Migration', () { - testWithoutContext('fails if Xcode project not found', () async { + testWithoutContext('skips if swift package manager is off', () async { final MemoryFileSystem memoryFileSystem = MemoryFileSystem(); final BufferLogger testLogger = BufferLogger.test(); @@ -39,6 +44,66 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: FakePlistParser(), + features: TestFeatureFlags(), + ); + await projectMigration.migrate(); + expect( + testLogger.traceText, + contains('Skipping the migration that adds Swift Package Manager integration...'), + ); + expect(testLogger.statusText, isEmpty); + }); + + testWithoutContext("skips if there's no generated swift package", () async { + final MemoryFileSystem memoryFileSystem = MemoryFileSystem(); + final BufferLogger testLogger = BufferLogger.test(); + + final SwiftPackageManagerIntegrationMigration projectMigration = SwiftPackageManagerIntegrationMigration( + FakeXcodeProject( + platform: SupportedPlatform.ios.name, + fileSystem: memoryFileSystem, + logger: testLogger, + ), + SupportedPlatform.ios, + BuildInfo.debug, + xcodeProjectInterpreter: FakeXcodeProjectInterpreter(), + logger: testLogger, + fileSystem: memoryFileSystem, + plistParser: FakePlistParser(), + features: swiftPackageManagerFullyEnabledFlags, + ); + await projectMigration.migrate(); + expect( + testLogger.traceText, + contains('Skipping the migration that adds Swift Package Manager integration...'), + ); + expect( + testLogger.traceText, + contains('The tool did not generate a Swift package.'), + ); + expect(testLogger.statusText, isEmpty); + }); + + testWithoutContext('fails if Xcode project not found', () async { + final MemoryFileSystem memoryFileSystem = MemoryFileSystem(); + final BufferLogger testLogger = BufferLogger.test(); + final FakeXcodeProject project = FakeXcodeProject( + platform: SupportedPlatform.ios.name, + fileSystem: memoryFileSystem, + logger: testLogger, + ); + + project.flutterPluginSwiftPackageManifest.createSync(recursive: true); + + final SwiftPackageManagerIntegrationMigration projectMigration = SwiftPackageManagerIntegrationMigration( + project, + SupportedPlatform.ios, + BuildInfo.debug, + xcodeProjectInterpreter: FakeXcodeProjectInterpreter(), + logger: testLogger, + fileSystem: memoryFileSystem, + plistParser: FakePlistParser(), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -68,6 +133,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: FakePlistParser(), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -96,6 +162,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: FakePlistParser(), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -129,6 +196,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: FakePlistParser(), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -160,6 +228,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: FakePlistParser(), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -194,6 +263,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: FakePlistParser(), + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); expect(testLogger.traceText, isEmpty); @@ -233,6 +303,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput(settingsAsJsonBeforeMigration), ), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater(() => projectMigration.migrate(), throwsToolExit()); expect( @@ -262,6 +333,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: FakePlistParser(), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -296,6 +368,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: FakePlistParser(), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( @@ -331,6 +404,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: FakePlistParser(), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( @@ -366,6 +440,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: FakePlistParser(), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( @@ -395,6 +470,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: FakePlistParser(), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( @@ -423,6 +499,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: FakePlistParser(), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( @@ -455,6 +532,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); @@ -489,6 +567,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); @@ -531,6 +610,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput(settingsAsJsonBeforeMigration), ), + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); expect( @@ -558,6 +638,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: FakePlistParser(), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -583,6 +664,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: FakePlistParser(json: '[]'), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -608,6 +690,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: FakePlistParser(json: 'this is not json'), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -636,6 +719,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: FakePlistParser(), + features: swiftPackageManagerFullyEnabledFlags, ); expect( () => projectMigration.migrate(), @@ -662,6 +746,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: FakePlistParser(), + features: swiftPackageManagerFullyEnabledFlags, ); expect( () => projectMigration.migrate(), @@ -688,6 +773,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: FakePlistParser(), + features: swiftPackageManagerFullyEnabledFlags, ); expect( () => projectMigration.migrate(), @@ -719,6 +805,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput([]), ), + features: swiftPackageManagerFullyEnabledFlags, ); expect( () => projectMigration.migrate(), @@ -760,6 +847,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput([]), ), + features: swiftPackageManagerFullyEnabledFlags, ); expect( () => projectMigration.migrate(), @@ -802,6 +890,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput([]), ), + features: swiftPackageManagerFullyEnabledFlags, ); expect( () => projectMigration.migrate(), @@ -844,6 +933,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); expect(testLogger.errorText, isEmpty); @@ -893,6 +983,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput(settingsAsJsonBeforeMigration), ), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -935,6 +1026,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput(settingsAsJsonBeforeMigration), ), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -981,6 +1073,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput(settingsAsJsonBeforeMigration), ), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -1020,6 +1113,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput(settingsAsJsonBeforeMigration), ), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -1075,6 +1169,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); expect(testLogger.errorText, isEmpty); @@ -1122,6 +1217,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); expect(testLogger.errorText, isEmpty); @@ -1184,6 +1280,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); expect(testLogger.errorText, isEmpty); @@ -1232,6 +1329,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput(settingsAsJsonBeforeMigration), ), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -1271,6 +1369,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput(settingsAsJsonBeforeMigration), ), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -1312,6 +1411,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput(settingsAsJsonBeforeMigration), ), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -1357,6 +1457,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput(settingsAsJsonBeforeMigration), ), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -1412,6 +1513,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); expect(testLogger.errorText, isEmpty); @@ -1460,6 +1562,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); expect(testLogger.errorText, isEmpty); @@ -1518,6 +1621,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); expect(testLogger.errorText, isEmpty); @@ -1566,6 +1670,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput(settingsAsJsonBeforeMigration), ), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -1609,6 +1714,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput(settingsAsJsonBeforeMigration), ), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -1656,6 +1762,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput(settingsAsJsonBeforeMigration), ), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -1695,6 +1802,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput(settingsAsJsonBeforeMigration), ), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -1752,6 +1860,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); expect(testLogger.errorText, isEmpty); @@ -1800,6 +1909,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); expect(testLogger.errorText, isEmpty); @@ -1858,6 +1968,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); expect(testLogger.errorText, isEmpty); @@ -1899,6 +2010,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput(settingsAsJsonBeforeMigration), ), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -1945,6 +2057,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); expect(testLogger.errorText, isEmpty); @@ -1993,6 +2106,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); expect(testLogger.errorText, isEmpty); @@ -2049,6 +2163,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); expect(testLogger.errorText, isEmpty); @@ -2090,6 +2205,7 @@ void main() { plistParser: FakePlistParser( json: _plutilOutput(settingsAsJsonBeforeMigration), ), + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -2131,6 +2247,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); expect(testLogger.errorText, isEmpty); @@ -2179,6 +2296,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); expect(testLogger.errorText, isEmpty); @@ -2235,6 +2353,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await projectMigration.migrate(); expect(testLogger.errorText, isEmpty); @@ -2276,6 +2395,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -2340,6 +2460,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, ); await expectLater( () => projectMigration.migrate(), @@ -2379,6 +2500,7 @@ void main() { logger: testLogger, fileSystem: memoryFileSystem, plistParser: plistParser, + features: swiftPackageManagerFullyEnabledFlags, validateBackup: true, ); await expectLater( @@ -2411,6 +2533,7 @@ void _createProjectFiles( project.parent.directory.createSync(recursive: true); project.hostAppRoot.createSync(recursive: true); project.xcodeProjectInfoFile.createSync(recursive: true); + project.flutterPluginSwiftPackageManifest.createSync(recursive: true); if (createSchemeFile) { project.xcodeProjectSchemeFile(scheme: scheme).createSync(recursive: true); project.xcodeProjectSchemeFile().writeAsStringSync( @@ -3229,6 +3352,7 @@ class FakeSwiftPackageManagerIntegrationMigration extends SwiftPackageManagerInt required super.logger, required super.fileSystem, required super.plistParser, + required super.features, this.validateBackup = false, }) : _xcodeProject = project; From 4426413ec6e70c732a53c74f28425002c9c6de63 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Mon, 18 Nov 2024 21:08:20 -0500 Subject: [PATCH 126/386] Roll Flutter Engine from 878f593802e1 to c1b0e18a70b3 (13 revisions) (#159118) https://github.com/flutter/engine/compare/878f593802e1...c1b0e18a70b3 2024-11-19 jonahwilliams@google.com [Impeller] use sync fence for image uploads. (flutter/engine#56609) 2024-11-18 reidbaker@google.com Update emulator definitions version to latest available from chrome infra (flutter/engine#56313) 2024-11-18 skia-flutter-autoroll@skia.org Roll Dart SDK from 625e0a9cb67a to 05d58364e92f (1 revision) (flutter/engine#56688) 2024-11-18 chris@bracken.jp iOS: Eliminate unguarded-availability opt-out (flutter/engine#56689) 2024-11-18 jacksongardner@google.com [skwasm] Use `displayWidth`/`displayHeight` instead of `codedWidth`/`codedHeight` (flutter/engine#56686) 2024-11-18 chris@bracken.jp Extract TestGLContext to separate translation unit (flutter/engine#56647) 2024-11-18 skia-flutter-autoroll@skia.org Roll Skia from b79e71223284 to 492e8347d7a4 (2 revisions) (flutter/engine#56687) 2024-11-18 jason-simmons@users.noreply.github.com Update the Skia build scripts for a refactoring of the Fontconfig font manager (flutter/engine#56684) 2024-11-18 chris@bracken.jp iOS,macOS: Enable ARC in flutter_cflags_objc[c] (flutter/engine#56685) 2024-11-18 matanlurey@users.noreply.github.com Re-land "Remove `android_jit_release_x86`." (flutter/engine#56681) 2024-11-18 skia-flutter-autoroll@skia.org Roll Skia from 0d24bd3268ef to b79e71223284 (1 revision) (flutter/engine#56683) 2024-11-18 tugorez@users.noreply.github.com Flutter views can gain focus (flutter/engine#54985) 2024-11-18 skia-flutter-autoroll@skia.org Roll Skia from 0b74d5c3eb4f to 0d24bd3268ef (1 revision) (flutter/engine#56680) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index ead9c298863..8ad9416bb7c 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -878f593802e16bbbc7fd7ff86c24a40302095e48 +c1b0e18a70b307012d723157122d31843ecc56b0 From 57dca6946d2e314958119e22e5b9cda7339075b9 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Mon, 18 Nov 2024 23:22:04 -0500 Subject: [PATCH 127/386] Roll Flutter Engine from c1b0e18a70b3 to 983b7b85d122 (2 revisions) (#159124) https://github.com/flutter/engine/compare/c1b0e18a70b3...983b7b85d122 2024-11-19 lhkbob@gmail.com Remove SK_USE_LEGACY_BLUR_RASTER staging flag (flutter/engine#56618) 2024-11-19 skia-flutter-autoroll@skia.org Roll Skia from 492e8347d7a4 to 8d652f142911 (1 revision) (flutter/engine#56693) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC jimgraham@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 8ad9416bb7c..4b3b9944597 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -c1b0e18a70b307012d723157122d31843ecc56b0 +983b7b85d12233c45e3de03e48af0a30ce0a0bfa From 966aeb28ea04d5166ad40a85ca20f7b093d70260 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Tue, 19 Nov 2024 04:17:26 -0500 Subject: [PATCH 128/386] Roll Flutter Engine from 983b7b85d122 to b6723e33b858 (3 revisions) (#159134) https://github.com/flutter/engine/compare/983b7b85d122...b6723e33b858 2024-11-19 skia-flutter-autoroll@skia.org Roll Skia from 17601e471acf to 8a1a84509501 (4 revisions) (flutter/engine#56700) 2024-11-19 skia-flutter-autoroll@skia.org Roll Skia from 8d652f142911 to 17601e471acf (1 revision) (flutter/engine#56696) 2024-11-19 robert.ancell@canonical.com Add missing cancellable to text input handler (flutter/engine#56666) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 4b3b9944597..97ead92c1ac 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -983b7b85d12233c45e3de03e48af0a30ce0a0bfa +b6723e33b858797e605e48baed1e973d76b68520 From 043c59b07525e849e6d12200c9ac97bf74a9b53f Mon Sep 17 00:00:00 2001 From: Bruno Leroux Date: Tue, 19 Nov 2024 12:33:40 +0100 Subject: [PATCH 129/386] Fix InkWell overlayColor resolution ignores selected state (#159072) ## Description This PR fixes `InkWell` overlay colors resolution. The `InkWell` overlay color is resolved when the `InkWell` is either focused, hovered , and/or pressed. This resolution happens at two places: - first when the highlight is created. - then on each build, using the inner function named `getHighlightColorForType`. This second resolution should be aware of other current states (such as selected) as it might impact the color resolution. For instance, several Material styles have colors resolution define similarly to: https://github.com/flutter/flutter/blob/dc44547d0d90dfff4fd4c3bdcd525f9d7a70744e/packages/flutter/lib/src/material/date_picker_theme.dart#L982-L1006 ## Related Issue Fixes [InkWell overlay colors aren't applied on MaterialState.selected state](https://github.com/flutter/flutter/issues/159063) First step for [Date picker overlay colors aren't applied on MaterialState.selected state](Date picker overlay colors aren't applied on MaterialState.selected state). ## Tests Adds 3 tests. --- .../flutter/lib/src/material/ink_well.dart | 14 +- .../flutter/test/material/ink_well_test.dart | 136 +++++++++++++++--- 2 files changed, 123 insertions(+), 27 deletions(-) diff --git a/packages/flutter/lib/src/material/ink_well.dart b/packages/flutter/lib/src/material/ink_well.dart index 4be927cf188..6a0e37cab57 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. 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(); From 87872a60953803898904ecf25fdc55ce43e9958e Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Tue, 19 Nov 2024 09:57:28 -0500 Subject: [PATCH 130/386] Roll Flutter Engine from b6723e33b858 to cff1e751f853 (1 revision) (#159141) https://github.com/flutter/engine/compare/b6723e33b858...cff1e751f853 2024-11-19 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from io00npG_eDCYC7bac... to dJ0gh-z1KVnSzvfjW... (flutter/engine#56701) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from io00npG_eDCY to dJ0gh-z1KVnS If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 97ead92c1ac..9ab078e8fed 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -b6723e33b858797e605e48baed1e973d76b68520 +cff1e751f85370f61ec02ecf10541cf4b66beb50 diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index 6ce43794467..9dcb5ea4a03 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -io00npG_eDCYC7bac6n1mLVKsJeKcBYdTUP0KLI7FvAC +dJ0gh-z1KVnSzvfjWj4xwwKr4dgSz1SnO7CjuQUqmzUC From eea2fe77815ea60554a63218b59b15af6e7be0de Mon Sep 17 00:00:00 2001 From: Reid Baker Date: Tue, 19 Nov 2024 10:35:58 -0500 Subject: [PATCH 131/386] Deflake api 35 emulator tests by updating emulator definitions version to latest available from chrome infra (#158017) Update to the latest definitions of emulator configurations. Specifically to past https://crrev.com/c/5908894 which added `gpu_mode: "swangle_indirect"` to the api 35 proto. This should help with emulator stability on versions past android 13. Related to b/371020223 Related: https://github.com/flutter/engine/pull/56313 Research notes / my findings for how this system works at go/flutter-android-ci-emulator ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide] and the [C++, Objective-C, Java style guides]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I added new tests to check the change I am making or feature I am adding, or the PR is [test-exempt]. See [testing the engine] for instructions on writing and running engine tests. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I signed the [CLA]. - [x] All existing and new tests are passing. --- .ci.yaml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.ci.yaml b/.ci.yaml index df589f42a29..6f1aa0f924f 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 @@ -412,7 +412,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"] @@ -1489,7 +1489,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 @@ -2240,7 +2240,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: > @@ -2653,7 +2653,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 From 0e1c6330ea7da210aac84cfb00d0ba484b1b1906 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Tue, 19 Nov 2024 10:44:31 -0500 Subject: [PATCH 132/386] Roll Packages from c1eabf5e32cc to fc4adc78aa24 (10 revisions) (#159143) https://github.com/flutter/packages/compare/c1eabf5e32cc...fc4adc78aa24 2024-11-18 magder@google.com [ci] Take screenshot when native drive test is taking longer than 10 minutes (flutter/packages#8050) 2024-11-18 jessiewong401@gmail.com Applied Gradle Plugins Declaratively for Most Remaining Plugin Example Apps (Part 3) (flutter/packages#8037) 2024-11-18 49699333+dependabot[bot]@users.noreply.github.com [pigeon]: Bump org.jetbrains.kotlin:kotlin-bom from 1.8.10 to 2.0.21 in /packages/pigeon/platform_tests/test_plugin/android (flutter/packages#7867) 2024-11-18 49699333+dependabot[bot]@users.noreply.github.com [gradle]: Bump androidx.test.ext:junit-ktx from 1.1.5 to 1.2.1 in /packages/shared_preferences/shared_preferences_android/android (flutter/packages#8097) 2024-11-18 49699333+dependabot[bot]@users.noreply.github.com [pigeon]: Bump org.jetbrains.kotlin:kotlin-gradle-plugin from 2.0.20 to 2.0.21 in /packages/pigeon/platform_tests/test_plugin/android (flutter/packages#7869) 2024-11-18 49699333+dependabot[bot]@users.noreply.github.com [gradle]: Bump org.hamcrest:hamcrest from 2.2 to 3.0 in /packages/espresso/android (flutter/packages#8092) 2024-11-18 49699333+dependabot[bot]@users.noreply.github.com [pigeon]: Bump io.mockk:mockk from 1.13.12 to 1.13.13 in /packages/pigeon/platform_tests/test_plugin/android (flutter/packages#7868) 2024-11-18 49699333+dependabot[bot]@users.noreply.github.com [shared_pref]: Bump io.mockk:mockk from 1.13.12 to 1.13.13 in /packages/shared_preferences/shared_preferences_android/android (flutter/packages#7866) 2024-11-18 magder@google.com Add autosubmit label to dependabot PRs (flutter/packages#8101) 2024-11-18 engine-flutter-autoroll@skia.org Roll Flutter from 0e2d55e0e7b2 to b3818f6b5979 (23 revisions) (flutter/packages#8118) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-packages-flutter-autoroll Please CC flutter-ecosystem@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/flutter_packages.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/flutter_packages.version b/bin/internal/flutter_packages.version index ec2c735f144..fa2da0fa644 100644 --- a/bin/internal/flutter_packages.version +++ b/bin/internal/flutter_packages.version @@ -1 +1 @@ -c1eabf5e32cccfe54474726584ea1c2cf5a0a269 +fc4adc78aa2417fad51c776dc54cc35115635080 From c5379557b3b10d354de60758dba9c14e6bf9e7a8 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Tue, 19 Nov 2024 08:10:32 -0800 Subject: [PATCH 133/386] Terminate the test device if the `flutter` tool is signal-killed. (#159115) Closes https://github.com/flutter/flutter/issues/20949. Signals (such as SIGTERM or SIGKILL) end up flowing through `exitWithHooks`, which in turn, after running hooks, call `exit().` That means, as a result, any `try { } finally { }` guarded execution may _not_ run, which happens to also be how `flutter_tester` instances are cleaned up if they have not terminated. This PR adds in-progress `flutter_tester` runs (or any platform `flutter_platform` supports) to the shutdown hooks, guaranteeing that the finalizers (which in turn, kill the process) are _always_ executed as long as either the test completes, _or_ `exitWithHooks` is called. The existing integration tests (`integration.shard/test_test.dart`) still pass as well. --- .../lib/src/test/flutter_platform.dart | 48 ++++++++++++------ .../general.shard/flutter_platform_test.dart | 49 +++++++++++++++++++ 2 files changed, 81 insertions(+), 16 deletions(-) diff --git a/packages/flutter_tools/lib/src/test/flutter_platform.dart b/packages/flutter_tools/lib/src/test/flutter_platform.dart index 1e3e2b4a034..6260cc9aa89 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'; @@ -307,6 +308,7 @@ class FlutterPlatform extends PlatformPlugin { this.testTimeRecorder, this.nativeAssetsBuilder, this.buildInfo, + this.shutdownHooks, }); final String shellPath; @@ -325,6 +327,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. /// @@ -476,8 +479,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(() { @@ -608,21 +638,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/test/general.shard/flutter_platform_test.dart b/packages/flutter_tools/test/general.shard/flutter_platform_test.dart index 98c9afd81a8..6a8d5fbfdab 100644 --- a/packages/flutter_tools/test/general.shard/flutter_platform_test.dart +++ b/packages/flutter_tools/test/general.shard/flutter_platform_test.dart @@ -7,6 +7,7 @@ import 'package:flutter_tools/src/application_package.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/base/process.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/device.dart'; import 'package:flutter_tools/src/flutter_manifest.dart'; @@ -97,6 +98,35 @@ void main() { ApplicationPackageFactory: () => _FakeApplicationPackageFactory(), }); + testUsingContext('a shutdown signal terminates the test device', () async { + final _WorkingDevice testDevice = _WorkingDevice(); + + final ShutdownHooks shutdownHooks = ShutdownHooks(); + final FlutterPlatform flutterPlatform = FlutterPlatform( + debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), + shellPath: '/', + enableVmService: false, + integrationTestDevice: testDevice, + flutterProject: _FakeFlutterProject(), + host: InternetAddress.anyIPv4, + updateGoldens: false, + shutdownHooks: shutdownHooks, + ); + + await expectLater( + () => flutterPlatform.loadChannel('test1.dart', fakeSuitePlatform).stream.drain(), + returnsNormally, + ); + + final BufferLogger logger = globals.logger as BufferLogger; + await shutdownHooks.runShutdownHooks(logger); + expect(logger.traceText, contains('test 0: ensuring test device is terminated.')); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => FakeProcessManager.any(), + ApplicationPackageFactory: () => _FakeApplicationPackageFactory(), + }); + testUsingContext('installHook creates a FlutterPlatform', () { expect(() => installHook( shellPath: 'abc', @@ -214,6 +244,25 @@ class _UnstartableDevice extends Fake implements Device { } } +class _WorkingDevice extends Fake implements Device { + @override + Future dispose() async {} + + @override + Future get targetPlatform => Future.value(TargetPlatform.android); + + @override + Future stopApp(ApplicationPackage? app, {String? userIdentifier}) async => true; + + @override + Future uninstallApp(ApplicationPackage app, {String? userIdentifier}) async => true; + + @override + Future startApp(covariant ApplicationPackage? package, {String? mainPath, String? route, required DebuggingOptions debuggingOptions, Map platformArgs = const {}, bool prebuiltApplication = false, String? userIdentifier}) async { + return LaunchResult.succeeded(vmServiceUri: Uri.parse('http://127.0.0.1:12345/vmService')); + } +} + class _FakeFlutterProject extends Fake implements FlutterProject { @override FlutterManifest get manifest => FlutterManifest.empty(logger: BufferLogger.test()); From 8536b96ebb3eaaebdc34a56b862b33bbc2d79a75 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Tue, 19 Nov 2024 08:16:08 -0800 Subject: [PATCH 134/386] Terminate `flutter test` when no longer needed in integration test. (#159117) Towards https://github.com/flutter/flutter/issues/51421. ```sh flutter_tools % dart test test/integration.shard/break_on_framework_exceptions_test.dart 02:38 +29: All tests passed! 54692 ttys003 0:00.02 /opt/homebrew/bin/zsh -il ``` Requires https://github.com/flutter/flutter/pull/159115 for the process cleanup to work properly, but this is safe to land as-is, otherwise we still accumulate `flutter` processes over and over as each test case runs which is not WAI. --- .../break_on_framework_exceptions_test.dart | 34 +++++++++++-------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/packages/flutter_tools/test/integration.shard/break_on_framework_exceptions_test.dart b/packages/flutter_tools/test/integration.shard/break_on_framework_exceptions_test.dart index dd699b5a463..c6591810e94 100644 --- a/packages/flutter_tools/test/integration.shard/break_on_framework_exceptions_test.dart +++ b/packages/flutter_tools/test/integration.shard/break_on_framework_exceptions_test.dart @@ -33,23 +33,29 @@ void main() { final FlutterTestTestDriver flutter = FlutterTestTestDriver(tempDir); - await _timeoutAfter( - message: 'Timed out launching `flutter test`', - work: () => flutter.test(withDebugger: true, pauseOnExceptions: true), - ); + try { + await _timeoutAfter( + message: 'Timed out launching `flutter test`', + work: () => flutter.test(withDebugger: true, pauseOnExceptions: true), + ); - await _timeoutAfter( - message: 'Timed out waiting for VM service pause debug event', - work: flutter.waitForPause, - ); + await _timeoutAfter( + message: 'Timed out waiting for VM service pause debug event', + work: flutter.waitForPause, + ); - int? breakLine; - await _timeoutAfter( - message: 'Timed out getting source location of top stack frame', - work: () async => breakLine = (await flutter.getSourceLocation())?.line, - ); + int? breakLine; + await _timeoutAfter( + message: 'Timed out getting source location of top stack frame', + work: () async => breakLine = (await flutter.getSourceLocation())?.line, + ); - expect(breakLine, project.lineContaining(project.test, exceptionMessage)); + expect(breakLine, project.lineContaining(project.test, exceptionMessage)); + } finally { + // Some of the tests will quit naturally, and others won't. + // By this point we don't need the tool anymore, so just force quit. + await flutter.quit(); + } } testWithoutContext('breaks when AnimationController listener throws', () async { From 56cfef73fcde34c3ada950f1c53c640add23079b Mon Sep 17 00:00:00 2001 From: Taha Tesser Date: Tue, 19 Nov 2024 21:10:44 +0200 Subject: [PATCH 135/386] Introduce new Material 3 `Slider` shapes (#152237) fixes [Update `Slider` for Material 3 redesign](https://github.com/flutter/flutter/issues/141842) previous implementation https://github.com/flutter/flutter/pull/147783 ### Description This PR introduces new Material 3 Slider design. ### Slider Preview Screenshot 2024-07-24 at 16 38 11 Screenshot 2024-07-24 at 16 38 24 ### Value indicator Preview https://github.com/user-attachments/assets/45fa001c-de81-433a-a8e9-6c0d6a2335c0 ### New stop indicator https://github.com/user-attachments/assets/ad05621d-042d-4b17-9dbb-7f7b802a2593 ### Customized Screenshot 2024-07-24 at 16 41 49 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [ ] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- dev/tools/gen_defaults/bin/gen_defaults.dart | 4 +- .../gen_defaults/generated/used_tokens.csv | 27 + .../gen_defaults/lib/slider_template.dart | 64 ++- packages/flutter/lib/src/material/slider.dart | 259 +++++++-- .../lib/src/material/slider_theme.dart | 494 +++++++++++++++++- .../flutter/test/material/slider_test.dart | 206 ++++++++ .../test/material/slider_theme_test.dart | 169 ++++++ 7 files changed, 1171 insertions(+), 52 deletions(-) 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/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/packages/flutter/lib/src/material/slider.dart b/packages/flutter/lib/src/material/slider.dart index c666e1d5407..a90119040c3 100644 --- a/packages/flutter/lib/src/material/slider.dart +++ b/packages/flutter/lib/src/material/slider.dart @@ -197,6 +197,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 = true, }) : _sliderType = _SliderType.material, assert(min <= max), assert(value >= min && value <= max, @@ -238,6 +243,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 = true, }) : _sliderType = _SliderType.adaptive, padding = null, assert(min <= max), @@ -432,9 +442,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 +566,18 @@ class Slider extends StatefulWidget { /// overlay shape, whichever is larger. final EdgeInsetsGeometry? padding; + /// When true, the [Slider] will use the 2023 Material 3 esign appearance. + /// + /// Defaults to true. If false, the [Slider] will use the latest Material 3 + /// Design 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 +810,12 @@ 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 SliderThemeData defaults = switch (theme.useMaterial3) { + true => widget.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 +824,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 +838,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 +880,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 +1714,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 +1728,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 +1839,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 +2012,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 +2062,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 +2149,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..500fb5fc979 100644 --- a/packages/flutter/lib/src/material/slider_theme.dart +++ b/packages/flutter/lib/src/material/slider_theme.dart @@ -297,6 +297,8 @@ class SliderThemeData with Diagnosticable { this.mouseCursor, this.allowedInteraction, this.padding, + this.thumbSize, + this.trackGap, }); /// Generates a SliderThemeData from three main colors. @@ -597,6 +599,30 @@ 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; + /// Creates a copy of this object but with the given fields replaced with the /// new values. SliderThemeData copyWith({ @@ -633,6 +659,8 @@ class SliderThemeData with Diagnosticable { MaterialStateProperty? mouseCursor, SliderInteraction? allowedInteraction, EdgeInsetsGeometry? padding, + MaterialStateProperty? thumbSize, + double? trackGap, }) { return SliderThemeData( trackHeight: trackHeight ?? this.trackHeight, @@ -668,6 +696,8 @@ class SliderThemeData with Diagnosticable { mouseCursor: mouseCursor ?? this.mouseCursor, allowedInteraction: allowedInteraction ?? this.allowedInteraction, padding: padding ?? this.padding, + thumbSize: thumbSize ?? this.thumbSize, + trackGap: trackGap ?? this.trackGap, ); } @@ -712,6 +742,8 @@ 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), ); } @@ -750,6 +782,8 @@ class SliderThemeData with Diagnosticable { mouseCursor, allowedInteraction, padding, + thumbSize, + trackGap, ), ); @@ -794,7 +828,9 @@ 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; } @override @@ -834,6 +870,8 @@ 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)); } } @@ -3559,3 +3597,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/test/material/slider_test.dart b/packages/flutter/test/material/slider_test.dart index a1be488cbdb..09711842cb8 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 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, + ) + ); + + // 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..815c643986c 100644 --- a/packages/flutter/test/material/slider_theme_test.dart +++ b/packages/flutter/test/material/slider_theme_test.dart @@ -2640,6 +2640,175 @@ void main() { ); }); + testWidgets('Can customize track gap when year2023 is false', (WidgetTester tester) async { + debugDisableShadows = false; + try { + Widget buildSlider({ double? trackGap }) { + return MaterialApp( + theme: ThemeData( + sliderTheme: SliderThemeData( + trackGap: trackGap, + ), + ), + home: Directionality( + textDirection: TextDirection.ltr, + child: 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 trackInnerCornderRadius = Radius.circular(2.0); + expect( + material, + paints + // Active track. + ..rrect( + rrect: RRect.fromLTRBAndCorners( + 24.0, 292.0, 400.0, 308.0, + topLeft: trackOuterCornerRadius, + topRight: trackInnerCornderRadius, + bottomRight: trackInnerCornderRadius, + bottomLeft: trackOuterCornerRadius, + ), + ) + // Inctive track. + ..rrect( + rrect: RRect.fromLTRBAndCorners( + 400.0, 292.0, 776.0, 308.0, + topLeft: trackInnerCornderRadius, + topRight: trackOuterCornerRadius, + bottomRight: trackOuterCornerRadius, + bottomLeft: trackInnerCornderRadius, + ), + ) + ); + + 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: trackInnerCornderRadius, + bottomRight: trackInnerCornderRadius, + bottomLeft: trackOuterCornerRadius, + ), + ) + // Inctive track. + ..rrect( + rrect: RRect.fromLTRBAndCorners( + 410.0, 292.0, 776.0, 308.0, + topLeft: trackInnerCornderRadius, + topRight: trackOuterCornerRadius, + bottomRight: trackOuterCornerRadius, + bottomLeft: trackInnerCornderRadius, + ), + ) + ); + } finally { + debugDisableShadows = true; + } + }); + + testWidgets('Can customize thumb size when year2023 is false', (WidgetTester tester) async { + debugDisableShadows = false; + try { + Widget buildSlider({ WidgetStateProperty? thumbSize }) { + return MaterialApp( + theme: ThemeData( + sliderTheme: SliderThemeData( + thumbSize: thumbSize, + ), + ), + home: Directionality( + textDirection: TextDirection.ltr, + child: 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(); + } finally { + debugDisableShadows = true; + } + }); + group('Material 2', () { // These tests are only relevant for Material 2. Once Material 2 // support is deprecated and the APIs are removed, these tests From fc53c713815301ba455a7909c539180889a382c6 Mon Sep 17 00:00:00 2001 From: Mairramer <50643541+Mairramer@users.noreply.github.com> Date: Tue, 19 Nov 2024 16:11:00 -0300 Subject: [PATCH 136/386] Fixes initial validation with AutovalidateMode.always on first build (#156708) Fixes #142701 This PR fixes an issue where on the first build `AutovalidateMode.always` was not called. ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [ ] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- packages/flutter/lib/src/widgets/form.dart | 33 +++++++++------ .../test/material/time_picker_test.dart | 2 - .../test/material/time_picker_theme_test.dart | 2 - packages/flutter/test/widgets/form_test.dart | 40 +++++++++++++++++++ 4 files changed, 60 insertions(+), 17 deletions(-) diff --git a/packages/flutter/lib/src/widgets/form.dart b/packages/flutter/lib/src/widgets/form.dart index 7be29d6eaa4..8fe5cf786b1 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,22 +251,10 @@ 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 @@ -703,6 +692,25 @@ 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(); @@ -749,7 +757,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/test/material/time_picker_test.dart b/packages/flutter/test/material/time_picker_test.dart index 07b43390593..bbdbacc6aca 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)); }); 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/widgets/form_test.dart b/packages/flutter/test/widgets/form_test.dart index 9785d7c28d2..5a3117d47d7 100644 --- a/packages/flutter/test/widgets/form_test.dart +++ b/packages/flutter/test/widgets/form_test.dart @@ -1457,4 +1457,44 @@ 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); + }); } From 1d01955721fbb5a3cde5beb6e0a0216b457d35ae Mon Sep 17 00:00:00 2001 From: Mohellebi abdessalem Date: Tue, 19 Nov 2024 20:32:22 +0100 Subject: [PATCH 137/386] Removing redundant backticks in `flutter\packages\flutter_tools\gradle\gradle.kts` (#159051) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `what android studio lint is failing ?` ![Capture d’écran 2024-11-19 110315](https://github.com/user-attachments/assets/d86605f6-0060-4721-9233-09d8ec5774d4) ![Capture d’écran 2024-11-19 110338](https://github.com/user-attachments/assets/7ee7465e-7a06-43db-bebb-ca87dda3cdc8) see #147122 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [ ] I updated/added relevant documentation (doc comments with `///`). - [ ] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- packages/flutter_tools/gradle/build.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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" From 41006014abc1352e29cc5f0eacdd66dff173ba74 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Tue, 19 Nov 2024 14:38:09 -0500 Subject: [PATCH 138/386] Roll Flutter Engine from cff1e751f853 to d5820a638885 (5 revisions) (#159155) https://github.com/flutter/engine/compare/cff1e751f853...d5820a638885 2024-11-19 skia-flutter-autoroll@skia.org Roll Skia from 0b74a1bb1b55 to 78ef6b7a574f (6 revisions) (flutter/engine#56707) 2024-11-19 chris@bracken.jp Move renderer config to EmbedderTestContext (flutter/engine#56699) 2024-11-19 skia-flutter-autoroll@skia.org Roll Skia from 8a1a84509501 to 0b74a1bb1b55 (1 revision) (flutter/engine#56702) 2024-11-19 skia-flutter-autoroll@skia.org Roll Dart SDK from 05d58364e92f to b01654fa26c7 (1 revision) (flutter/engine#56694) 2024-11-19 chris@bracken.jp EmbedderTest: Eliminate unused include (flutter/engine#56698) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 9ab078e8fed..b6fa05f10bb 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -cff1e751f85370f61ec02ecf10541cf4b66beb50 +d5820a638885bff8642a5e8ee9c206880d44a94e From f0dc0b798f9d47135c48b6404855c62ff23fa0fa Mon Sep 17 00:00:00 2001 From: Mohellebi abdessalem Date: Tue, 19 Nov 2024 21:32:05 +0100 Subject: [PATCH 139/386] fix lint usage of `task` inside `resolve_dependecies.gradle` file (#158022) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit according to [Gradle](https://docs.gradle.org/current/userguide/task_configuration_avoidance.htmll) :`As of Gradle 5.1, we recommend that the configuration avoidance APIs be used whenever tasks are created.` ![writing-tasks-4](https://github.com/user-attachments/assets/407c79bb-7bfa-4bea-9b13-dec01c60dc1c) what android studio lint is failing ? ![Capture d’écran 2024-11-01 214856](https://github.com/user-attachments/assets/af745305-6310-406c-b427-fb8a5dd5755c) ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [ ] I updated/added relevant documentation (doc comments with `///`). - [ ] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- packages/flutter_tools/gradle/resolve_dependencies.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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() From 1fdb159d118779315bdd27fbc86533800e41d88a Mon Sep 17 00:00:00 2001 From: Bernardo Ferrari Date: Tue, 19 Nov 2024 17:47:15 -0300 Subject: [PATCH 140/386] Reland Add UI Benchmarks (#153368) Reland https://github.com/flutter/flutter/pull/143799 which is part 1 of https://github.com/flutter/flutter/pull/138481 and https://github.com/flutter/flutter/issues/146211. Could someone run this in device-lab so we are 100% sure it works? I don't know if it was a flake or what last time. Locally it works well. --- .../lib/benchmark_collection.dart | 2 + .../lib/foundation/observer_list_bench.dart | 172 ++++++++++++++++++ 2 files changed, 174 insertions(+) create mode 100644 dev/benchmarks/microbenchmarks/lib/foundation/observer_list_bench.dart diff --git a/dev/benchmarks/microbenchmarks/lib/benchmark_collection.dart b/dev/benchmarks/microbenchmarks/lib/benchmark_collection.dart index 02efa6c2b2e..e1c201df18f 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 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..ac492c4b7f7 --- /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 runNotifiyListenersLoopWithObserverList( + 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 runNotifiyListenersLoopWithHashedObserverList( + 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 runNotifiyListenersLoopWithAnimationController( + 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', + ); + } + } + } + + runNotifiyListenersLoopWithObserverList(_kNumIterationsList); + runNotifiyListenersLoopWithObserverList(_kNumIterationsList, + failRemoval: true); + runNotifiyListenersLoopWithHashedObserverList(_kNumIterationsHashed); + runNotifiyListenersLoopWithAnimationController(_kNumIterationsHashed); + + printer.printToStdout(); +} From 79c5ae0c7af574a90e36244fc123c00557395e8a Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Tue, 19 Nov 2024 15:51:18 -0500 Subject: [PATCH 141/386] Roll Flutter Engine from d5820a638885 to 4ff696b555dc (1 revision) (#159164) https://github.com/flutter/engine/compare/d5820a638885...4ff696b555dc 2024-11-19 47866232+chunhtai@users.noreply.github.com Update Engine-Clang-Tidy-Linter.md (flutter/engine#56708) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index b6fa05f10bb..1cbcf47c736 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -d5820a638885bff8642a5e8ee9c206880d44a94e +4ff696b555dc5ce0f30d48730646d5b2251d105d From c12f75066dfc0e88ceaffa5e49f6dbae86912ad5 Mon Sep 17 00:00:00 2001 From: Jenn Magder Date: Tue, 19 Nov 2024 13:53:38 -0800 Subject: [PATCH 142/386] Add platform-android label for all flutter_tools *android* files (#159166) Label PRs that touch any `*android*` files in flutter_tool with `platform-android`. In particular this should catch the template android directories. Labeler log: https://github.com/flutter/flutter/actions/runs/11921551623/job/33225914301?pr=159166#step:2:240
Included files ``` $ git ls-files 'packages/flutter_tools/*android**' packages/flutter_tools/ide_templates/intellij/dev/manual_tests/android.iml.copy.tmpl packages/flutter_tools/ide_templates/intellij/examples/flutter_gallery/android.iml.copy.tmpl packages/flutter_tools/ide_templates/intellij/examples/hello_world/android.iml.copy.tmpl packages/flutter_tools/ide_templates/intellij/examples/platform_channel/android.iml.copy.tmpl packages/flutter_tools/ide_templates/intellij/examples/platform_view/android.iml.copy.tmpl packages/flutter_tools/ide_templates/intellij/examples/stocks/android.iml.copy.tmpl packages/flutter_tools/lib/src/android/README.md packages/flutter_tools/lib/src/android/adb.dart packages/flutter_tools/lib/src/android/android.dart packages/flutter_tools/lib/src/android/android_builder.dart packages/flutter_tools/lib/src/android/android_console.dart packages/flutter_tools/lib/src/android/android_device.dart packages/flutter_tools/lib/src/android/android_device_discovery.dart packages/flutter_tools/lib/src/android/android_emulator.dart packages/flutter_tools/lib/src/android/android_sdk.dart packages/flutter_tools/lib/src/android/android_studio.dart packages/flutter_tools/lib/src/android/android_studio_validator.dart packages/flutter_tools/lib/src/android/android_workflow.dart packages/flutter_tools/lib/src/android/application_package.dart packages/flutter_tools/lib/src/android/build_validation.dart packages/flutter_tools/lib/src/android/deferred_components_gen_snapshot_validator.dart packages/flutter_tools/lib/src/android/deferred_components_prebuild_validator.dart packages/flutter_tools/lib/src/android/deferred_components_validator.dart packages/flutter_tools/lib/src/android/gradle.dart packages/flutter_tools/lib/src/android/gradle_errors.dart packages/flutter_tools/lib/src/android/gradle_utils.dart packages/flutter_tools/lib/src/android/java.dart packages/flutter_tools/lib/src/android/migrations/android_studio_java_gradle_conflict_migration.dart packages/flutter_tools/lib/src/android/migrations/cmake_android_16k_pages_migration.dart packages/flutter_tools/lib/src/android/migrations/min_sdk_version_migration.dart packages/flutter_tools/lib/src/android/migrations/multidex_removal_migration.dart packages/flutter_tools/lib/src/android/migrations/top_level_gradle_build_file_migration.dart packages/flutter_tools/lib/src/build_system/targets/android.dart packages/flutter_tools/lib/src/commands/android_analyze.dart packages/flutter_tools/lib/src/isolated/native_assets/android/native_assets.dart packages/flutter_tools/templates/app_shared/android-java.tmpl/app/build.gradle.kts.tmpl packages/flutter_tools/templates/app_shared/android-java.tmpl/app/src/main/java/androidIdentifier/MainActivity.java.tmpl packages/flutter_tools/templates/app_shared/android-java.tmpl/build.gradle.kts.tmpl packages/flutter_tools/templates/app_shared/android-java.tmpl/projectName_android.iml.tmpl packages/flutter_tools/templates/app_shared/android-kotlin.tmpl/app/build.gradle.kts.tmpl packages/flutter_tools/templates/app_shared/android-kotlin.tmpl/app/src/main/kotlin/androidIdentifier/MainActivity.kt.tmpl packages/flutter_tools/templates/app_shared/android-kotlin.tmpl/build.gradle.kts.tmpl packages/flutter_tools/templates/app_shared/android-kotlin.tmpl/projectName_android.iml.tmpl packages/flutter_tools/templates/app_shared/android.tmpl/.gitignore packages/flutter_tools/templates/app_shared/android.tmpl/app/src/debug/AndroidManifest.xml.tmpl packages/flutter_tools/templates/app_shared/android.tmpl/app/src/main/AndroidManifest.xml.tmpl packages/flutter_tools/templates/app_shared/android.tmpl/app/src/main/res/drawable-v21/launch_background.xml packages/flutter_tools/templates/app_shared/android.tmpl/app/src/main/res/drawable/launch_background.xml packages/flutter_tools/templates/app_shared/android.tmpl/app/src/main/res/mipmap-hdpi/ic_launcher.png packages/flutter_tools/templates/app_shared/android.tmpl/app/src/main/res/mipmap-mdpi/ic_launcher.png packages/flutter_tools/templates/app_shared/android.tmpl/app/src/main/res/mipmap-xhdpi/ic_launcher.png packages/flutter_tools/templates/app_shared/android.tmpl/app/src/main/res/mipmap-xxhdpi/ic_launcher.png packages/flutter_tools/templates/app_shared/android.tmpl/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png packages/flutter_tools/templates/app_shared/android.tmpl/app/src/main/res/values-night/styles.xml packages/flutter_tools/templates/app_shared/android.tmpl/app/src/main/res/values/styles.xml packages/flutter_tools/templates/app_shared/android.tmpl/app/src/profile/AndroidManifest.xml.tmpl packages/flutter_tools/templates/app_shared/android.tmpl/gradle.properties.tmpl packages/flutter_tools/templates/app_shared/android.tmpl/gradle/wrapper/gradle-wrapper.properties.tmpl packages/flutter_tools/templates/app_shared/android.tmpl/settings.gradle.kts.tmpl packages/flutter_tools/templates/module/android/deferred_component/build.gradle.tmpl packages/flutter_tools/templates/module/android/deferred_component/src/main/AndroidManifest.xml.tmpl packages/flutter_tools/templates/module/android/gradle/build.gradle.tmpl packages/flutter_tools/templates/module/android/gradle/gradle.properties.tmpl packages/flutter_tools/templates/module/android/gradle/settings.gradle.tmpl packages/flutter_tools/templates/module/android/gradle/src/main/AndroidManifest.xml.tmpl packages/flutter_tools/templates/module/android/host_app_common/app.tmpl/build.gradle.tmpl packages/flutter_tools/templates/module/android/host_app_common/app.tmpl/src/main/AndroidManifest.xml.tmpl packages/flutter_tools/templates/module/android/host_app_common/app.tmpl/src/main/java/androidIdentifier/host/MainActivity.java.tmpl packages/flutter_tools/templates/module/android/host_app_common/app.tmpl/src/main/res/drawable/launch_background.xml packages/flutter_tools/templates/module/android/host_app_common/app.tmpl/src/main/res/mipmap-hdpi/ic_launcher.png packages/flutter_tools/templates/module/android/host_app_common/app.tmpl/src/main/res/values/styles.xml packages/flutter_tools/templates/module/android/host_app_editable/settings.gradle.copy.tmpl packages/flutter_tools/templates/module/android/host_app_ephemeral/settings.gradle.copy.tmpl packages/flutter_tools/templates/module/android/library_new_embedding/Flutter.tmpl/build.gradle.tmpl packages/flutter_tools/templates/module/android/library_new_embedding/Flutter.tmpl/flutter.iml.copy.tmpl packages/flutter_tools/templates/module/android/library_new_embedding/Flutter.tmpl/src/main/AndroidManifest.xml.tmpl packages/flutter_tools/templates/module/android/library_new_embedding/include_flutter.groovy.copy.tmpl packages/flutter_tools/templates/module/android/library_new_embedding/settings.gradle.copy.tmpl packages/flutter_tools/templates/module/common/projectName_android.iml.tmpl packages/flutter_tools/templates/plugin/android-java.tmpl/build.gradle.tmpl packages/flutter_tools/templates/plugin/android-java.tmpl/projectName_android.iml.tmpl packages/flutter_tools/templates/plugin/android-java.tmpl/src/main/java/androidIdentifier/pluginClass.java.tmpl packages/flutter_tools/templates/plugin/android-java.tmpl/src/test/java/androidIdentifier/pluginClassTest.java.tmpl packages/flutter_tools/templates/plugin/android-kotlin.tmpl/build.gradle.tmpl packages/flutter_tools/templates/plugin/android-kotlin.tmpl/projectName_android.iml.tmpl packages/flutter_tools/templates/plugin/android-kotlin.tmpl/src/main/kotlin/androidIdentifier/pluginClass.kt.tmpl packages/flutter_tools/templates/plugin/android-kotlin.tmpl/src/test/kotlin/androidIdentifier/pluginClassTest.kt.tmpl packages/flutter_tools/templates/plugin/android.tmpl/.gitignore packages/flutter_tools/templates/plugin/android.tmpl/settings.gradle.tmpl packages/flutter_tools/templates/plugin/android.tmpl/src/main/AndroidManifest.xml.tmpl packages/flutter_tools/templates/plugin_ffi/android.tmpl/build.gradle.tmpl packages/flutter_tools/templates/plugin_ffi/android.tmpl/projectName_android.iml.tmpl packages/flutter_tools/templates/plugin_shared/android.tmpl/.gitignore packages/flutter_tools/templates/plugin_shared/android.tmpl/settings.gradle.tmpl packages/flutter_tools/templates/plugin_shared/android.tmpl/src/main/AndroidManifest.xml.tmpl packages/flutter_tools/test/android_java11_integration.shard/android_dependency_version_checking_test.dart packages/flutter_tools/test/android_preview_integration.shard/README.md packages/flutter_tools/test/android_preview_integration.shard/flutter_build_preview_sdk_test.dart packages/flutter_tools/test/commands.shard/hermetic/android_analyze_test.dart packages/flutter_tools/test/general.shard/android/adb_log_reader_test.dart packages/flutter_tools/test/general.shard/android/android_device_discovery_test.dart packages/flutter_tools/test/general.shard/android/android_device_port_forwarder_test.dart packages/flutter_tools/test/general.shard/android/android_device_start_test.dart packages/flutter_tools/test/general.shard/android/android_device_test.dart packages/flutter_tools/test/general.shard/android/android_emulator_test.dart packages/flutter_tools/test/general.shard/android/android_gradle_builder_test.dart packages/flutter_tools/test/general.shard/android/android_install_test.dart packages/flutter_tools/test/general.shard/android/android_project_migration_test.dart packages/flutter_tools/test/general.shard/android/android_sdk_test.dart packages/flutter_tools/test/general.shard/android/android_studio_test.dart packages/flutter_tools/test/general.shard/android/android_studio_validator_test.dart packages/flutter_tools/test/general.shard/android/android_workflow_test.dart packages/flutter_tools/test/general.shard/android/build_validation_test.dart packages/flutter_tools/test/general.shard/android/deferred_components_gen_snapshot_validator_test.dart packages/flutter_tools/test/general.shard/android/deferred_components_prebuild_validator_test.dart packages/flutter_tools/test/general.shard/android/gradle_errors_test.dart packages/flutter_tools/test/general.shard/android/gradle_find_bundle_test.dart packages/flutter_tools/test/general.shard/android/gradle_test.dart packages/flutter_tools/test/general.shard/android/gradle_utils_test.dart packages/flutter_tools/test/general.shard/android/java_test.dart packages/flutter_tools/test/general.shard/android/migration/cmake_android_16k_pages_migration_test.dart packages/flutter_tools/test/general.shard/android/template_test.dart packages/flutter_tools/test/general.shard/android_plugin_test.dart packages/flutter_tools/test/general.shard/build_system/targets/android_test.dart packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart packages/flutter_tools/test/integration.shard/android_gradle_daemon_cache_test.dart packages/flutter_tools/test/integration.shard/android_gradle_deprecated_plugin_apply_test.dart packages/flutter_tools/test/integration.shard/android_gradle_flutter_source_path_test.dart packages/flutter_tools/test/integration.shard/android_gradle_java_version_test.dart packages/flutter_tools/test/integration.shard/android_gradle_legacy_flutter_plugins_strings_in_comments_test.dart packages/flutter_tools/test/integration.shard/android_gradle_outputs_app_link_settings_test.dart packages/flutter_tools/test/integration.shard/android_gradle_print_build_variants_test.dart packages/flutter_tools/test/integration.shard/android_plugin_compilesdkversion_mismatch_test.dart packages/flutter_tools/test/integration.shard/android_plugin_example_app_build_test.dart packages/flutter_tools/test/integration.shard/android_plugin_ndkversion_mismatch_test.dart packages/flutter_tools/test/integration.shard/android_plugin_new_output_dir_test.dart packages/flutter_tools/test/integration.shard/android_plugin_skip_unsupported_test.dart packages/flutter_tools/test/integration.shard/flutter_build_android_app_project_builddir_test.dart packages/flutter_tools/test/integration.shard/gradle_non_android_plugin_test.dart packages/flutter_tools/test/src/android_common.dart ```
Expand https://github.com/flutter/flutter/pull/158970 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- .github/labeler.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/labeler.yml b/.github/labeler.yml index c83124b35de..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,7 +138,7 @@ platform-android: - changed-files: - any-glob-to-any-file: - docs/platform/android/**/* - - packages/flutter_tools/lib/src/android/**/* + - packages/flutter_tools/*android*' - packages/flutter_tools/gradle/**/* platform-ios: From a1c7a0dda48f2f5d7c6674032878a41e7e86d13f Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Tue, 19 Nov 2024 16:55:12 -0500 Subject: [PATCH 143/386] Roll Flutter Engine from 4ff696b555dc to 7eb87547cbc6 (3 revisions) (#159168) https://github.com/flutter/engine/compare/4ff696b555dc...7eb87547cbc6 2024-11-19 chris@bracken.jp EmbedderTest: templatise GetEmbedderContext (flutter/engine#56709) 2024-11-19 chris@bracken.jp display_list: Extract backend-specific surface providers (flutter/engine#56711) 2024-11-19 skia-flutter-autoroll@skia.org Roll Skia from 78ef6b7a574f to a694b9e85a49 (5 revisions) (flutter/engine#56713) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 1cbcf47c736..f4ea969d1d2 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -4ff696b555dc5ce0f30d48730646d5b2251d105d +7eb87547cbc6139dab7e5ae9bfda9514114b1546 From 1686fa7eb4eaeca0955719668e8316a3b0a3a3af Mon Sep 17 00:00:00 2001 From: Taha Tesser Date: Wed, 20 Nov 2024 01:23:26 +0200 Subject: [PATCH 144/386] Update Material 3 `CircularProgressIndicator` for new visual style (#158104) Related [Update both `ProgressIndicator` for Material 3 redesign](https://github.com/flutter/flutter/issues/141340) Fixes [Issue: Cannot theme progress indicators, many properties missing](https://github.com/flutter/flutter/issues/131690) Fixes [Cannot override default `CircularProgressIndicator` size](https://github.com/flutter/flutter/issues/158106) ### Code sample
expand to view the code sample ```dart import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatefulWidget { const MyApp({super.key}); @override State createState() => _MyAppState(); } class _MyAppState extends State { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( // progressIndicatorTheme: const ProgressIndicatorThemeData( // constraints: BoxConstraints.tightFor(width: 100, height: 100), // strokeWidth: 12 // ), ), home: Scaffold( appBar: AppBar(title: const Text('CircularProgressIndicator')), body: const Center( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ CircularProgressIndicator(year2023: false, value: 0.5), CircularProgressIndicator(year2023: false), ], ), ), ), ); } } ```
### Preview Screenshot 2024-11-04 at 16 01 57 ### New custom `CircularProgressIndicator.constraints` and stroke width Screenshot 2024-11-04 at 16 02 40 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [ ] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- .../lib/progress_indicator_template.dart | 20 +- .../lib/src/material/progress_indicator.dart | 272 ++++++++++++++---- .../material/progress_indicator_theme.dart | 45 ++- .../material/progress_indicator_test.dart | 166 ++++++++++- .../progress_indicator_theme_test.dart | 164 ++++++++++- 5 files changed, 607 insertions(+), 60 deletions(-) diff --git a/dev/tools/gen_defaults/lib/progress_indicator_template.dart b/dev/tools/gen_defaults/lib/progress_indicator_template.dart index 82e1a8b13ba..d7a1effaefc 100644 --- a/dev/tools/gen_defaults/lib/progress_indicator_template.dart +++ b/dev/tools/gen_defaults/lib/progress_indicator_template.dart @@ -12,16 +12,32 @@ 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: 48.0, + minHeight: 48.0, + ); + + @override + double? get trackGap => ${getToken('md.comp.progress-indicator.active-indicator-track-space')}; } class _Linear${blockName}DefaultsM3 extends ProgressIndicatorThemeData { diff --git a/packages/flutter/lib/src/material/progress_indicator.dart b/packages/flutter/lib/src/material/progress_indicator.dart index 0b454bda51d..c8fd9aef7cb 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; @@ -550,7 +549,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 +559,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 +568,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 +580,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 +604,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 +668,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 +677,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; } } @@ -698,19 +733,28 @@ 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 = true, }) : _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 +766,14 @@ 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 = true, }) : _indicatorType = _ActivityIndicatorType.adaptive; final _ActivityIndicatorType _indicatorType; @@ -738,16 +789,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 +824,36 @@ 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 3 + /// Design appearance. + /// + /// Defaults to true. If false, the [CircularProgressIndicator] will use the + /// latest Material 3 Design 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 indicator stroke is drawn fully inside of the indicator path. /// /// This is a constant for use with [strokeAlign]. @@ -857,30 +941,50 @@ 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 defaults = switch (Theme.of(context).useMaterial3) { + true => widget.year2023 + ? _CircularProgressIndicatorDefaultsM3Year2023(context, indeterminate: widget.value == null) + : _CircularProgressIndicatorDefaultsM3(context, indeterminate: widget.value == null), + false => _CircularProgressIndicatorDefaultsM2(context, indeterminate: widget.value == null), + }; + final ProgressIndicatorThemeData indicatorTheme = ProgressIndicatorTheme.of(context); + 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 = widget.year2023 + ? null + : widget.trackGap ?? + indicatorTheme.trackGap ?? + defaults.trackGap; return widget._buildSemanticsWrapper( context: context, child: ConstrainedBox( - constraints: const BoxConstraints( - minWidth: _kMinCircularProgressIndicatorSize, - minHeight: _kMinCircularProgressIndicatorSize, - ), + constraints: constraints, child: CustomPaint( painter: _CircularProgressIndicatorPainter( - backgroundColor: trackColor, + 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: widget.strokeWidth, - strokeAlign: widget.strokeAlign, - strokeCap: widget.strokeCap, + strokeWidth: strokeWidth, + strokeAlign: strokeAlign, + strokeCap: strokeCap, + trackGap: trackGap, + year2023: widget.year2023, ), ), ), @@ -1128,10 +1232,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 +1273,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 +1291,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 +1329,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 +1376,32 @@ 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: 48.0, + minHeight: 48.0, + ); + + @override + double? get trackGap => 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..31df16a02ba 100644 --- a/packages/flutter/lib/src/material/progress_indicator_theme.dart +++ b/packages/flutter/lib/src/material/progress_indicator_theme.dart @@ -42,6 +42,10 @@ class ProgressIndicatorThemeData with Diagnosticable { this.borderRadius, this.stopIndicatorColor, this.stopIndicatorRadius, + this.strokeWidth, + this.strokeAlign, + this.strokeCap, + this.constraints, this.trackGap, }); @@ -85,7 +89,22 @@ 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. @@ -102,6 +121,10 @@ class ProgressIndicatorThemeData with Diagnosticable { BorderRadiusGeometry? borderRadius, Color? stopIndicatorColor, double? stopIndicatorRadius, + double? strokeWidth, + double? strokeAlign, + StrokeCap? strokeCap, + BoxConstraints? constraints, double? trackGap, }) { return ProgressIndicatorThemeData( @@ -113,6 +136,10 @@ 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, ); } @@ -133,6 +160,10 @@ 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), ); } @@ -147,6 +178,10 @@ class ProgressIndicatorThemeData with Diagnosticable { borderRadius, stopIndicatorColor, stopIndicatorRadius, + strokeAlign, + strokeWidth, + strokeCap, + constraints, trackGap, ); @@ -167,6 +202,10 @@ class ProgressIndicatorThemeData with Diagnosticable { && other.borderRadius == borderRadius && other.stopIndicatorColor == stopIndicatorColor && other.stopIndicatorRadius == stopIndicatorRadius + && other.strokeAlign == strokeAlign + && other.strokeWidth == strokeWidth + && other.strokeCap == strokeCap + && other.constraints == constraints && other.trackGap == trackGap; } @@ -181,6 +220,10 @@ 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)); } } diff --git a/packages/flutter/test/material/progress_indicator_test.dart b/packages/flutter/test/material/progress_indicator_test.dart index e5558b07b33..103e9396e88 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)); @@ -1551,6 +1564,151 @@ void main() { ), ); }); + + testWidgets('Default determinate CircularProgressIndicator when year2023 is false', (WidgetTester tester) async { + await tester.pumpWidget(MaterialApp( + theme: theme, + home: const Center( + child: CircularProgressIndicator( + year2023: false, + value: 0.5, + ), + ), + )); + + expect(tester.getSize(find.byType(CircularProgressIndicator)), equals(const Size(48, 48))); + expect( + find.byType(CircularProgressIndicator), + paints + // Track. + ..arc( + rect: const Rect.fromLTRB(2.0, 2.0, 46.0, 46.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, 46.0, 46.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 { + await tester.pumpWidget(MaterialApp( + theme: theme, + home: const Center(child: CircularProgressIndicator(year2023: false)), + )); + + // Advance the animation. + await tester.pump(const Duration(milliseconds: 200)); + + expect(tester.getSize(find.byType(CircularProgressIndicator)), equals(const Size(48, 48))); + expect( + find.byType(CircularProgressIndicator), + paints + // Active indicator. + ..arc( + rect: const Rect.fromLTRB(2.0, 2.0, 46.0, 46.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)); + }); } 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..8f85a64ab0e 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,46 @@ 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, + ).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' + ])); + }); + testWidgets('Can theme LinearProgressIndicator using ProgressIndicatorTheme', (WidgetTester tester) async { const Color color = Color(0XFF00FF00); const Color linearTrackColor = Color(0XFFFF0000); @@ -62,7 +109,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 +229,119 @@ 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); + final ThemeData theme = ThemeData( + progressIndicatorTheme: const ProgressIndicatorThemeData( + color: color, + circularTrackColor: circularTrackColor, + strokeWidth: strokeWidth, + strokeAlign: strokeAlign, + strokeCap: strokeCap, + constraints: constraints, + ), + ); + 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, constraints.maxHeight)), + ); + 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; + final ThemeData theme = ThemeData( + progressIndicatorTheme: const ProgressIndicatorThemeData( + color: color, + circularTrackColor: circularTrackColor, + strokeWidth: strokeWidth, + strokeAlign: strokeAlign, + strokeCap: strokeCap, + constraints: constraints, + trackGap: trackGap, + ), + ); + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: const Scaffold( + body: Center( + child: CircularProgressIndicator( + year2023: false, + value: 0.5, + ), + ), + ), + ), + ); + + expect( + tester.getSize(find.byType(CircularProgressIndicator)), + equals(Size(constraints.maxWidth, constraints.maxHeight)), + ); + 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'), + ); + }); } From 1fdcb757fde4ab590844770e2c5d12d2434f873d Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Tue, 19 Nov 2024 16:11:39 -0800 Subject: [PATCH 145/386] Make `runner` non-nullable as it always is. (#159156) --- .../flutter_tools/lib/src/commands/attach.dart | 2 +- .../flutter_tools/lib/src/commands/daemon.dart | 18 +++++++++++------- .../flutter_tools/lib/src/commands/run.dart | 2 +- 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/packages/flutter_tools/lib/src/commands/attach.dart b/packages/flutter_tools/lib/src/commands/attach.dart index 2ad5dc1632f..c5b4dd6501e 100644 --- a/packages/flutter_tools/lib/src/commands/attach.dart +++ b/packages/flutter_tools/lib/src/commands/attach.dart @@ -372,7 +372,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) { diff --git a/packages/flutter_tools/lib/src/commands/daemon.dart b/packages/flutter_tools/lib/src/commands/daemon.dart index 6749b988fea..98e81cf1c41 100644 --- a/packages/flutter_tools/lib/src/commands/daemon.dart +++ b/packages/flutter_tools/lib/src/commands/daemon.dart @@ -902,7 +902,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! @@ -1550,20 +1550,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/run.dart b/packages/flutter_tools/lib/src/commands/run.dart index 4b9cb710bf1..f2e6d16474f 100644 --- a/packages/flutter_tools/lib/src/commands/run.dart +++ b/packages/flutter_tools/lib/src/commands/run.dart @@ -771,7 +771,7 @@ class RunCommand extends RunCommandBase { 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); } From 0234757554d64038b644f51d8ff6bd2b00dbed9a Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Tue, 19 Nov 2024 19:21:22 -0500 Subject: [PATCH 146/386] Roll Flutter Engine from 7eb87547cbc6 to 3f19207e820e (4 revisions) (#159176) https://github.com/flutter/engine/compare/7eb87547cbc6...3f19207e820e 2024-11-19 skia-flutter-autoroll@skia.org Roll Skia from d776efdac21b to 2614590b4f32 (1 revision) (flutter/engine#56718) 2024-11-19 chris@bracken.jp TestMetalContext: Use ARC-managed Metal types (flutter/engine#56717) 2024-11-19 skia-flutter-autoroll@skia.org Roll Skia from a694b9e85a49 to d776efdac21b (3 revisions) (flutter/engine#56716) 2024-11-19 skia-flutter-autoroll@skia.org Roll Dart SDK from b01654fa26c7 to dde57dc75c15 (3 revisions) (flutter/engine#56714) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index f4ea969d1d2..c1ab2f9fca6 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -7eb87547cbc6139dab7e5ae9bfda9514114b1546 +3f19207e820eadee033f7e403a9fe7be69f90fb1 From 15a03a4adac970940eec3c4472037406d308d329 Mon Sep 17 00:00:00 2001 From: HongeSun <63278936+hongeSunCoder@users.noreply.github.com> Date: Wed, 20 Nov 2024 14:32:04 +0800 Subject: [PATCH 147/386] Fix git command in Quality-Assurance.md (#155146) Correct the Quality-Assurance contributing doc's wrong git command. ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] All existing and new tests are passing. --- docs/releases/Quality-Assurance.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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: From e2d8121708e2153315e0f722606ddd1e2506d83b Mon Sep 17 00:00:00 2001 From: Martin Kustermann Date: Wed, 20 Nov 2024 13:44:43 +0100 Subject: [PATCH 148/386] Remove dependency on [Target] and instead operate on [Architecture] (#159196) The dart-lang/native repository contains a `Target` class that is almost not needed anymore. The remaining uses are mainly due to kernel asset mapping (which we may be able to remove in the future). This PR removes usages of that `Target` (in favor of `Architecture`) class in most places in flutter tools. This makes the code also cleaner because we no longer have an implicit assumption that a `List` all belong to the same operating system. --- .../native_assets/android/native_assets.dart | 32 ++++----- .../native_assets/ios/native_assets.dart | 10 +-- .../native_assets/macos/native_assets.dart | 8 +-- .../isolated/native_assets/native_assets.dart | 65 ++++++++++--------- .../isolated/android/native_assets_test.dart | 4 +- .../isolated/ios/native_assets_test.dart | 4 +- .../isolated/macos/native_assets_test.dart | 8 +-- .../isolated/windows/native_assets_test.dart | 11 ++-- 8 files changed, 73 insertions(+), 69 deletions(-) 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 fb3634365dc..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 @@ -34,7 +34,7 @@ Future copyNativeCodeAssetsAndroid( final Uri source = assetMapping.key.file!; final Uri target = (assetMapping.value.path as KernelAssetAbsolutePath).uri; final AndroidArch androidArch = - _getAndroidArch(assetMapping.value.target); + _getAndroidArch(assetMapping.value.target.architecture); final String jniArchDir = androidArch.archName; final Uri archUri = buildUri.resolve('jniLibs/lib/$jniArchDir/'); final Uri targetUri = archUri.resolveUri(target); @@ -43,25 +43,25 @@ Future copyNativeCodeAssetsAndroid( } } -/// 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 76842bcd8fb..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 @@ -20,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, }; } 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 700157416fa..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 @@ -13,11 +13,11 @@ 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.'), }; } 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 5c989071564..686e0007dbf 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 @@ -96,16 +96,16 @@ Future runFlutterSpecificDartBuild({ return const DartBuildResult.empty(); } - final build_info.BuildMode buildMode = _getBuildMode(targetPlatform, environmentDefines, flutterTester); - 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, @@ -124,7 +124,7 @@ Future installCodeAssets({ final OS targetOS = getNativeOSFromTargetPlatfrorm(targetPlatform); final Uri buildUri = nativeAssetsBuildUri(projectUri, targetOS); final bool flutterTester = targetPlatform == build_info.TargetPlatform.tester; - final build_info.BuildMode buildMode = _getBuildMode(targetPlatform, environmentDefines, flutterTester); + final build_info.BuildMode buildMode = _getBuildMode(environmentDefines, flutterTester); final String? codesignIdentity = environmentDefines[build_info.kCodesignIdentity]; final Map assetTargetLocations = assetTargetLocationsForOS(targetOS, dartBuildResult.codeAssets, flutterTester, buildUri); @@ -711,20 +711,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]; @@ -748,12 +751,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, @@ -770,7 +773,7 @@ Future _runDartBuild({ applicationAssetValidator: (List assets) async => [ ...await validateCodeAssetInApplication(assets), ], - targetOS: target.os, + targetOS: targetOS!, buildMode: buildMode, workingDirectory: projectUri, includeParentEnvironment: true, @@ -787,7 +790,7 @@ Future _runDartBuild({ supportedAssetTypes: [CodeAsset.type], configCreator: () => LinkConfigBuilder() ..setupCodeConfig( - targetArchitecture: target.architecture, + targetArchitecture: architecture, linkModePreference: LinkModePreference.dynamic, cCompilerConfig: cCompilerConfig, targetAndroidNdkApi: androidNdkApi, @@ -823,7 +826,7 @@ 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()); } @@ -865,13 +868,13 @@ Future _runDartDryRunBuild({ 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]) @@ -882,7 +885,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]; @@ -890,7 +893,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]) @@ -898,24 +901,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: @@ -1097,7 +1098,7 @@ const Map> _osTargets = >{ }, }; -build_info.BuildMode _getBuildMode(build_info.TargetPlatform targetPlatform, Map environmentDefines, bool isFlutterTester) { +build_info.BuildMode _getBuildMode(Map environmentDefines, bool isFlutterTester) { if (isFlutterTester) { return build_info.BuildMode.debug; } diff --git a/packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart index 34bfa478b8b..1a26d82d227 100644 --- a/packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart @@ -111,8 +111,8 @@ void main() { expect( (globals.logger as BufferLogger).traceText, stringContainsInOrder([ - 'Building native assets for android_arm64 $buildMode.', - 'Building native assets for android_arm64 $buildMode done.', + 'Building native assets for android arm64 $buildMode.', + 'Building native assets for android arm64 $buildMode done.', ]), ); diff --git a/packages/flutter_tools/test/general.shard/isolated/ios/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/ios/native_assets_test.dart index 141703026e2..8997038b651 100644 --- a/packages/flutter_tools/test/general.shard/isolated/ios/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/ios/native_assets_test.dart @@ -216,8 +216,8 @@ void main() { expect( (globals.logger as BufferLogger).traceText, stringContainsInOrder([ - 'Building native assets for [ios_arm64, ios_x64] $buildMode.', - 'Building native assets for [ios_arm64, ios_x64] $buildMode done.', + 'Building native assets for ios [arm64, x64] $buildMode.', + 'Building native assets for ios [arm64, x64] $buildMode done.', ]), ); expect(environment.buildDir.childFile(InstallCodeAssets.nativeAssetsFilename), exists); diff --git a/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_test.dart index c674cca87e2..58c151e8697 100644 --- a/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_test.dart @@ -323,13 +323,13 @@ void main() { nativeAssetsFileUri: nativeAssetsFileUri , ); final String expectedArchsBeingBuilt = flutterTester - ? (isArm64 ? 'macos_arm64' : 'macos_x64') - : '[macos_arm64, macos_x64]'; + ? (isArm64 ? 'arm64' : 'x64') + : '[arm64, x64]'; expect( (globals.logger as BufferLogger).traceText, stringContainsInOrder([ - 'Building native assets for $expectedArchsBeingBuilt $buildMode.', - 'Building native assets for $expectedArchsBeingBuilt $buildMode done.', + 'Building native assets for macos $expectedArchsBeingBuilt $buildMode.', + 'Building native assets for macos $expectedArchsBeingBuilt $buildMode done.', ]), ); final String nativeAssetsFileContent = await fileSystem.file(nativeAssetsFileUri).readAsString(); diff --git a/packages/flutter_tools/test/general.shard/isolated/windows/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/windows/native_assets_test.dart index c05c308a6a9..9f9b6db1c0f 100644 --- a/packages/flutter_tools/test/general.shard/isolated/windows/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/windows/native_assets_test.dart @@ -127,13 +127,16 @@ void main() { nativeAssetsFileUri: nativeAssetsFileUri, ); final String expectedOS = flutterTester - ? native_assets_cli.Target.current.toString() - : 'windows_x64'; + ? OS.current.toString() + : 'windows'; + final String expectedArch = flutterTester + ? Architecture.current.toString() + : 'x64'; expect( (globals.logger as BufferLogger).traceText, stringContainsInOrder([ - 'Building native assets for $expectedOS $buildMode.', - 'Building native assets for $expectedOS $buildMode done.', + 'Building native assets for $expectedOS $expectedArch $buildMode.', + 'Building native assets for $expectedOS $expectedArch $buildMode done.', ]), ); expect( From 1c79e33741d81beb0f9f3ad6af4be914abe38341 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Wed, 20 Nov 2024 10:44:31 -0500 Subject: [PATCH 149/386] Roll Packages from fc4adc78aa24 to e95f6d8fce58 (6 revisions) (#159201) https://github.com/flutter/packages/compare/fc4adc78aa24...e95f6d8fce58 2024-11-19 louisehsu@google.com [in_app_purchase_storekit] disallow ios versions lower than supported from enabling storekit (flutter/packages#8110) 2024-11-19 49699333+dependabot[bot]@users.noreply.github.com [interactive_media_ads]: Bump com.google.ads.interactivemedia.v3:interactivemedia from 3.35.1 to 3.36.0 in /packages/interactive_media_ads/android (flutter/packages#8046) 2024-11-19 49699333+dependabot[bot]@users.noreply.github.com [interactive_media_ads]: Bump androidx.annotation:annotation from 1.8.2 to 1.9.1 in /packages/interactive_media_ads/android (flutter/packages#7980) 2024-11-19 10687576+bparrishMines@users.noreply.github.com [webview_flutter_android] Updates plugin to use `ProxyApis`s (flutter/packages#7794) 2024-11-19 10687576+bparrishMines@users.noreply.github.com [interactive_media_ads] Adds support to define parameters that control the rendering of ads (flutter/packages#8057) 2024-11-19 engine-flutter-autoroll@skia.org Roll Flutter from b3818f6b5979 to 8536b96ebb3e (22 revisions) (flutter/packages#8124) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-packages-flutter-autoroll Please CC flutter-ecosystem@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/flutter_packages.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/flutter_packages.version b/bin/internal/flutter_packages.version index fa2da0fa644..8ac8998018f 100644 --- a/bin/internal/flutter_packages.version +++ b/bin/internal/flutter_packages.version @@ -1 +1 @@ -fc4adc78aa2417fad51c776dc54cc35115635080 +e95f6d8fce589a6dfbd8ceb6f2ddaa537ec2b2e6 From 1894436ec3a4b95d6c8b58d2c0907e613383b7c5 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Wed, 20 Nov 2024 13:29:12 -0500 Subject: [PATCH 150/386] Roll Flutter Engine from 3f19207e820e to 80d77505fdde (1 revision) (#159210) https://github.com/flutter/engine/compare/3f19207e820e...80d77505fdde 2024-11-20 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from dJ0gh-z1KVnSzvfjW... to oq6Ztlu1b1mgdDSPH... (flutter/engine#56728) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from dJ0gh-z1KVnS to oq6Ztlu1b1mg If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index c1ab2f9fca6..b76312b6acb 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -3f19207e820eadee033f7e403a9fe7be69f90fb1 +80d77505fdde270f51ec814df76d861db26b1013 diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index 9dcb5ea4a03..5cb06ba673b 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -dJ0gh-z1KVnSzvfjWj4xwwKr4dgSz1SnO7CjuQUqmzUC +oq6Ztlu1b1mgdDSPHcGPu9oR19woqUEXinAJnHoE6scC From 3f1ea760e8fe08284947ef7eb3eaafdefc12f4b0 Mon Sep 17 00:00:00 2001 From: StanleyCocos Date: Thu, 21 Nov 2024 03:23:24 +0800 Subject: [PATCH 151/386] =?UTF-8?q?Fix:=20The=20enableFeedback=20property?= =?UTF-8?q?=20of=20InkWell=20cannot=20be=20set=20to=20a=20nullab=E2=80=A6?= =?UTF-8?q?=20(#158907)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit *I found that enableFeedback can be set to null, but in actual use, setting it to null has no effect and is overwritten by true. I think this is an issue.* ```dart class InkWell extends InkResponse { const InkWell({ super.key, super.child, super.onTap, super.onDoubleTap, super.onLongPress, super.onTapDown, super.onTapUp, super.onTapCancel, super.onSecondaryTap, super.onSecondaryTapUp, super.onSecondaryTapDown, super.onSecondaryTapCancel, super.onHighlightChanged, super.onHover, super.mouseCursor, super.focusColor, super.hoverColor, super.highlightColor, super.overlayColor, super.splashColor, super.splashFactory, super.radius, super.borderRadius, super.customBorder, bool? enableFeedback = true, super.excludeFromSemantics, super.focusNode, super.canRequestFocus, super.onFocusChange, super.autofocus, super.statesController, super.hoverDuration, }) : super( containedInkWell: true, highlightShape: BoxShape.rectangle, enableFeedback: enableFeedback ?? true, ); } ``` Call Error ```dart InkWell( enableFeedback: null, ) ``` --- packages/flutter/lib/src/material/button_style_button.dart | 2 +- packages/flutter/lib/src/material/ink_well.dart | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/flutter/lib/src/material/button_style_button.dart b/packages/flutter/lib/src/material/button_style_button.dart index 74cf34c3f69..3684e13dd26 100644 --- a/packages/flutter/lib/src/material/button_style_button.dart +++ b/packages/flutter/lib/src/material/button_style_button.dart @@ -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/ink_well.dart b/packages/flutter/lib/src/material/ink_well.dart index 6a0e37cab57..831776bdfb6 100644 --- a/packages/flutter/lib/src/material/ink_well.dart +++ b/packages/flutter/lib/src/material/ink_well.dart @@ -1462,7 +1462,7 @@ class InkWell extends InkResponse { super.radius, super.borderRadius, super.customBorder, - bool? enableFeedback = true, + super.enableFeedback, super.excludeFromSemantics, super.focusNode, super.canRequestFocus, @@ -1473,6 +1473,5 @@ class InkWell extends InkResponse { }) : super( containedInkWell: true, highlightShape: BoxShape.rectangle, - enableFeedback: enableFeedback ?? true, ); } From ae9c8e8e2e09c63b406c292f5237de50a0d10767 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Wed, 20 Nov 2024 14:42:36 -0500 Subject: [PATCH 152/386] Roll Flutter Engine from 80d77505fdde to 3245c8976976 (1 revision) (#159214) https://github.com/flutter/engine/compare/80d77505fdde...3245c8976976 2024-11-20 jonahwilliams@google.com [Impeller] flush all GLES cmd buffers together. (flutter/engine#56724) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index b76312b6acb..86044990c50 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -80d77505fdde270f51ec814df76d861db26b1013 +3245c8976976c70d54137d58362d3caefe111c71 From f2446f2dfba1b5d0cde91dfeba043c1742a145c2 Mon Sep 17 00:00:00 2001 From: Gray Mackall <34871572+gmackall@users.noreply.github.com> Date: Wed, 20 Nov 2024 12:58:39 -0800 Subject: [PATCH 153/386] Add docs for setting up Android Studio to auto format Kotlin code (#159209) Docs to make Android Studio auto format kotlin code in a way compatible with the format check that we make in CI. Open to suggestions as to a better place to put them, but there wasn't an existing doc that seemed like an obvious fit to me. ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [ ] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --------- Co-authored-by: Gray Mackall Co-authored-by: Reid Baker --- dev/bots/analyze.dart | 3 ++- .../Kotlin-android-studio-formatting.md | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 docs/platforms/android/Kotlin-android-studio-formatting.md diff --git a/dev/bots/analyze.dart b/dev/bots/analyze.dart index 7102ecb51ff..5663ac062eb 100644 --- a/dev/bots/analyze.dart +++ b/dev/bots/analyze.dart @@ -2126,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]); } } 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 +``` From bf36437cae4f4199d427ca5e5ba10ce6a4b6a6d2 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Wed, 20 Nov 2024 13:01:54 -0800 Subject: [PATCH 154/386] Add `--dry-run` to `dev/bots/test.dart`. (#158956) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes https://github.com/flutter/flutter/issues/158884. /cc @reidbaker. Example output: ```sh % SHARD=tool_integration_tests SUBSHARD=6_6 dart dev/bots/test.dart --dry-run ▌13:59:18▐ STARTING ANALYSIS ▌13:59:18▐ --dry-run enabled. Tests will not actually be executed. ▌13:59:18▐ SHARD=tool_integration_tests ▌13:59:18▐ SUBSHARD=6_6 ▌13:59:18▐ |> bin/flutter: --version ▌13:59:18▐ |> bin/cache/dart-sdk/bin/dart (packages/flutter_tools): run test --reporter=expanded --file-reporter=json:/var/folders/qw/qw_3qd1x4kz5w975jhdq4k58007b7h/T/metrics_1731621558619861.json --test-randomize-ordering-seed=20241114 -j1 test/integration.shard/shader_compiler_test.dart test/integration.shard/overall_experience_test.dart test/integration.shard/expression_evaluation_test.dart test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart test/integration.shard/isolated/native_assets_test.dart test/integration.shard/isolated/native_assets_agp_version_test.dart test/integration.shard/coverage_collection_test.dart test/integration.shard/devtools_uri_test.dart test/integration.shard/deprecated_gradle_settings_test.dart test/integration.shard/batch_entrypoint_test.dart test/integration.shard/bash_entrypoint_test.dart test/integration.shard/background_isolate_test.dart ``` --- dev/bots/run_command.dart | 26 ++++++++ dev/bots/suite_runners/run_web_tests.dart | 4 +- dev/bots/test.dart | 19 ++++-- dev/bots/test/test_test.dart | 9 +++ dev/bots/utils.dart | 76 ++++++++++++++++------- 5 files changed, 106 insertions(+), 28 deletions(-) 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_web_tests.dart b/dev/bots/suite_runners/run_web_tests.dart index 4064c8c27a8..d96c0467b2b 100644 --- a/dev/bots/suite_runners/run_web_tests.dart +++ b/dev/bots/suite_runners/run_web_tests.dart @@ -708,7 +708,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 0c9ff764d29..4077a937e15 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]}'); } @@ -541,6 +545,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 3ed0958ff02..8b089e58395 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 determing 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. @@ -413,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)); @@ -508,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); @@ -619,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]!(); } } From 53bd6435ae77b5d0f521c1bb67d06a88bddbe79e Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Wed, 20 Nov 2024 16:12:13 -0500 Subject: [PATCH 155/386] Roll Flutter Engine from 3245c8976976 to 3828681d1f86 (1 revision) (#159217) https://github.com/flutter/engine/compare/3245c8976976...3828681d1f86 2024-11-20 dacoharkes@google.com [et] Add Android x64 configurations (flutter/engine#56703) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 86044990c50..e3967d3043a 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -3245c8976976c70d54137d58362d3caefe111c71 +3828681d1f86610a09374e9976430cb291202fcb From 364e4be81638a3f109820135c32ffdd9d8ff87c9 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Wed, 20 Nov 2024 17:10:10 -0500 Subject: [PATCH 156/386] Roll Flutter Engine from 3828681d1f86 to 2d32cf3a7971 (3 revisions) (#159226) https://github.com/flutter/engine/compare/3828681d1f86...2d32cf3a7971 2024-11-20 flar@google.com [DisplayList] migrate DlImageFilter code to Impeller geometry classes (flutter/engine#56720) 2024-11-20 robert.ancell@canonical.com Split channel messaging out of handlers (flutter/engine#56667) 2024-11-20 jason-simmons@users.noreply.github.com Revert "Added assert for opengles thread safety (#56585)" (flutter/engine#56730) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index e3967d3043a..f0a033cb9b8 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -3828681d1f86610a09374e9976430cb291202fcb +2d32cf3a7971e375fb4147dc53137f5b6155d274 From 17e38a4b78a67d1c2f30c786fa69b22536444d5f Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Wed, 20 Nov 2024 18:30:38 -0500 Subject: [PATCH 157/386] Roll Flutter Engine from 2d32cf3a7971 to 69c325513a65 (1 revision) (#159229) https://github.com/flutter/engine/compare/2d32cf3a7971...69c325513a65 2024-11-20 dkwingsmt@users.noreply.github.com Fix: Impeller playground's shapes should react to controllers (flutter/engine#56734) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index f0a033cb9b8..a62ed3d6c22 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -2d32cf3a7971e375fb4147dc53137f5b6155d274 +69c325513a658177fb9b0f743cf9f0cbb1af70f0 From 1d24fa8f6088eb6e956a3d0877d2992c2f9f7fb2 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Wed, 20 Nov 2024 17:13:50 -0800 Subject: [PATCH 158/386] Un-skip tests that use `flutter build apk`. (#159231) Closes https://github.com/flutter/flutter/issues/158560. I believe but am not sure as of https://github.com/flutter/flutter/pull/159170 merging, many process flakes that were consuming memory and in turn, making Gradle particularly sensitive to timing out or being killing by the OS for low-memory, have been rectified. It is possible there are additional problems, but they aren't visible at the moment. I'd like to re-enable these and keep tracking their stability. --- .../test/integration.shard/isolated/native_assets_test.dart | 3 --- .../isolated/native_assets_without_cbuild_assemble_test.dart | 3 --- 2 files changed, 6 deletions(-) diff --git a/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart b/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart index 8d09e2af7db..e86fea21cea 100644 --- a/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart +++ b/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart @@ -223,9 +223,6 @@ void main() { expectCCompilerIsConfigured(exampleDirectory); }); }, - // TODO(matanlurey): Debug why flutter build apk often timesout. - // See https://github.com/flutter/flutter/issues/158560 for details. - skip: buildSubcommand == 'apk' ? 'flutter build apk times out' : false, // Temporary workaround for https://github.com/flutter/flutter/issues/158560. tags: ['flutter-build-apk'], ); } diff --git a/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart b/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart index 0b06f436bfa..81b1c050bae 100644 --- a/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart +++ b/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart @@ -143,9 +143,6 @@ void main(List args) async { expect(await process.exitCode, 0); },); }, - // TODO(matanlurey): Debug why flutter build apk often timesout. - // See https://github.com/flutter/flutter/issues/158560 for details. - skip: buildCommand == 'apk' ? 'flutter build apk times out' : false, // Temporary workaround for https://github.com/flutter/flutter/issues/158560. tags: ['flutter-build-apk'], ); } From 5ead4e15a7a99d59e77ac045389432f180c8bb12 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Wed, 20 Nov 2024 17:21:25 -0800 Subject: [PATCH 159/386] Terminate non-detached test devices on `flutter run` completion (#159170) See https://github.com/flutter/flutter/issues/159154. See https://github.com/flutter/flutter/pull/159169. Before this PR, it appeared we were accidentally leaking (keeping active) `flutter_tester` instances (or any test device) after `flutter run` completion, even if the runner was not explicitly detached. I _think_ this is a bug, but I'll check with the tools team and possibly @jonahwilliams before finalizing this. /cc @jason-simmons --------- Co-authored-by: Andrew Kolos --- .../lib/src/resident_runner.dart | 14 ++ packages/flutter_tools/lib/src/run_hot.dart | 32 +++-- .../test/general.shard/hot_shared.dart | 9 ++ .../resident_runner_helpers.dart | 3 + .../general.shard/resident_runner_test.dart | 8 ++ .../test/general.shard/run_hot_test.dart | 126 +++++++++++++++++- 6 files changed, 179 insertions(+), 13 deletions(-) diff --git a/packages/flutter_tools/lib/src/resident_runner.dart b/packages/flutter_tools/lib/src/resident_runner.dart index 2e2ee0dc98a..38dea5eceea 100644 --- a/packages/flutter_tools/lib/src/resident_runner.dart +++ b/packages/flutter_tools/lib/src/resident_runner.dart @@ -1118,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 @@ -1254,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(); @@ -1398,6 +1411,7 @@ abstract class ResidentRunner extends ResidentHandlers { } } + @protected void appFinished() { if (_finished.isCompleted) { return; diff --git a/packages/flutter_tools/lib/src/run_hot.dart b/packages/flutter_tools/lib/src/run_hot.dart index 9eb5fc121d0..1f8d040ca7c 100644 --- a/packages/flutter_tools/lib/src/run_hot.dart +++ b/packages/flutter_tools/lib/src/run_hot.dart @@ -125,9 +125,6 @@ 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; @@ -220,15 +217,29 @@ class HotRunner extends ResidentRunner { 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, @@ -464,7 +475,7 @@ class HotRunner extends ResidentRunner { return 1; } - return attach( + return _attach( connectionInfoCompleter: connectionInfoCompleter, appStartedCompleter: appStartedCompleter, needsFullRestart: false, @@ -1142,7 +1153,7 @@ class HotRunner extends ResidentRunner { } else { commandHelp.hWithoutDetails.print(); } - if (_didAttach) { + if (stopAppDuringCleanup) { commandHelp.d.print(); } commandHelp.c.print(); @@ -1239,11 +1250,10 @@ class HotRunner extends ResidentRunner { Future cleanupAfterSignal() async { await stopEchoingDeviceLog(); await hotRunnerConfig!.runPreShutdownOperations(); - if (_didAttach) { - appFinished(); - } else { - await exitApp(); + if (stopAppDuringCleanup) { + return exitApp(); } + appFinished(); } @override diff --git a/packages/flutter_tools/test/general.shard/hot_shared.dart b/packages/flutter_tools/test/general.shard/hot_shared.dart index 39f0aa0da57..5a1bda9d231 100644 --- a/packages/flutter_tools/test/general.shard/hot_shared.dart +++ b/packages/flutter_tools/test/general.shard/hot_shared.dart @@ -4,6 +4,7 @@ import 'package:flutter_tools/src/application_package.dart'; import 'package:flutter_tools/src/asset.dart'; +import 'package:flutter_tools/src/base/dds.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/build_system/tools/shader_compiler.dart'; import 'package:flutter_tools/src/compile.dart'; @@ -52,6 +53,9 @@ class FakeDevice extends Fake implements Device { bool disposed = false; + @override + final DartDevelopmentService dds = _FakeDartDevelopmentService(); + @override bool isSupported() => true; @@ -90,6 +94,11 @@ class FakeDevice extends Fake implements Device { } } +class _FakeDartDevelopmentService extends Fake implements DartDevelopmentService { + @override + void shutdown() {} +} + class FakeFlutterDevice extends Fake implements FlutterDevice { FakeFlutterDevice(this.device); diff --git a/packages/flutter_tools/test/general.shard/resident_runner_helpers.dart b/packages/flutter_tools/test/general.shard/resident_runner_helpers.dart index 1aa10fc0e99..bb24db978a9 100644 --- a/packages/flutter_tools/test/general.shard/resident_runner_helpers.dart +++ b/packages/flutter_tools/test/general.shard/resident_runner_helpers.dart @@ -146,6 +146,9 @@ class FakeDartDevelopmentService extends Fake with DartDevelopmentServiceLocalOp @override Uri? get uri => null; + + @override + void shutdown() {} } class FakeDartDevelopmentServiceException implements DartDevelopmentServiceException { diff --git a/packages/flutter_tools/test/general.shard/resident_runner_test.dart b/packages/flutter_tools/test/general.shard/resident_runner_test.dart index 275a5b6f24f..927e3b8f824 100644 --- a/packages/flutter_tools/test/general.shard/resident_runner_test.dart +++ b/packages/flutter_tools/test/general.shard/resident_runner_test.dart @@ -96,6 +96,12 @@ void main() { expect(fakeVmServiceHost?.hasRemainingExpectations, false); })); + testUsingContext('ResidentRunner reports whether detach() was used', () => testbed.run(() async { + expect(residentRunner.stopAppDuringCleanup, true); + await residentRunner.detach(); + expect(residentRunner.stopAppDuringCleanup, false); + })); + testUsingContext('ResidentRunner suppresses errors for the initial compilation', () => testbed.run(() async { globals.fs.file(globals.fs.path.join('lib', 'main.dart')) .createSync(recursive: true); @@ -1302,6 +1308,7 @@ flutter: commandHelp.M, commandHelp.g, commandHelp.hWithDetails, + commandHelp.d, commandHelp.c, commandHelp.q, '', @@ -1331,6 +1338,7 @@ flutter: commandHelp.r, commandHelp.R, commandHelp.hWithoutDetails, + commandHelp.d, commandHelp.c, commandHelp.q, '', diff --git a/packages/flutter_tools/test/general.shard/run_hot_test.dart b/packages/flutter_tools/test/general.shard/run_hot_test.dart index 163eeb0ec16..d1394c1a3ef 100644 --- a/packages/flutter_tools/test/general.shard/run_hot_test.dart +++ b/packages/flutter_tools/test/general.shard/run_hot_test.dart @@ -2,7 +2,12 @@ // 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/build_info.dart'; +import 'package:flutter_tools/src/compile.dart'; import 'package:flutter_tools/src/devfs.dart'; +import 'package:flutter_tools/src/device.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'; @@ -11,11 +16,13 @@ import 'package:test/fake.dart'; import 'package:unified_analytics/unified_analytics.dart'; import 'package:vm_service/vm_service.dart' as vm_service; -//import '../src/context.dart'; import '../src/common.dart'; +import '../src/context.dart'; +import 'hot_shared.dart'; void main() { - testWithoutContext('defaultReloadSourcesHelper() handles empty DeviceReloadReports)', () { + testWithoutContext( + 'defaultReloadSourcesHelper() handles empty DeviceReloadReports)', () { defaultReloadSourcesHelper( _FakeHotRunner(), [_FakeFlutterDevice()], @@ -29,6 +36,88 @@ void main() { const NoOpAnalytics(), ); }); + + group('signal handling', () { + late _FakeHotCompatibleFlutterDevice flutterDevice; + late MemoryFileSystem fileSystem; + + setUp(() { + flutterDevice = _FakeHotCompatibleFlutterDevice(FakeDevice()); + fileSystem = MemoryFileSystem.test(); + }); + + testUsingContext( + 'kills the test device', + () async { + final HotRunner runner = HotRunner( + [ + flutterDevice, + ], + target: 'main.dart', + debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), + analytics: _FakeAnalytics(), + ); + + await runner.run(); + await runner.cleanupAfterSignal(); + expect(flutterDevice.wasExited, true); + }, + overrides: { + FileSystem: () => fileSystem, + ProcessManager: FakeProcessManager.empty, + }, + ); + + testUsingContext( + 'kill with a detach keeps the test device running', + () async { + final HotRunner runner = HotRunner( + [ + flutterDevice, + ], + target: 'main.dart', + debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), + analytics: _FakeAnalytics(), + ); + + await runner.run(); + await runner.detach(); + await runner.cleanupAfterSignal(); + expect(flutterDevice.wasExited, false); + }, + overrides: { + FileSystem: () => fileSystem, + ProcessManager: FakeProcessManager.empty, + }, + ); + + testUsingContext( + 'kill on an attached device keeps the test device running', + () async { + final HotRunner runner = HotRunner( + [ + flutterDevice, + ], + target: 'main.dart', + debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), + analytics: _FakeAnalytics(), + ); + + await runner.attach(); + await runner.cleanupAfterSignal(); + expect(flutterDevice.wasExited, false); + }, + overrides: { + FileSystem: () => fileSystem, + ProcessManager: FakeProcessManager.empty, + }, + ); + }); +} + +class _FakeAnalytics extends Fake implements Analytics { + @override + void send(Event event) {} } class _FakeHotRunner extends Fake implements HotRunner {} @@ -37,6 +126,9 @@ class _FakeDevFS extends Fake implements DevFS { @override final Uri? baseUri = Uri(); + @override + Future destroy() async {} + @override void resetLastCompiled() {} } @@ -49,6 +141,36 @@ class _FakeFlutterDevice extends Fake implements FlutterDevice { final FlutterVmService? vmService = _FakeFlutterVmService(); } +class _FakeHotCompatibleFlutterDevice extends Fake implements FlutterDevice { + _FakeHotCompatibleFlutterDevice(this.device); + + @override + final Device device; + + @override + DevFS? devFS = _FakeDevFS(); + + @override + ResidentCompiler? get generator => null; + + @override + Future runHot({required HotRunner hotRunner, String? route}) async { + return 0; + } + + @override + Future stopEchoingDeviceLog() async {} + + @override + Future exitApps({ + Duration timeoutDelay = const Duration(seconds: 10), + }) async { + wasExited = true; + } + + bool wasExited = false; +} + class _FakeFlutterVmService extends Fake implements FlutterVmService { @override final vm_service.VmService service = _FakeVmService(); From b4736980190b77e8bd0f0c980261cc3ead793099 Mon Sep 17 00:00:00 2001 From: Justin McCandless Date: Wed, 20 Nov 2024 17:33:14 -0800 Subject: [PATCH 160/386] Scribe Android handwriting text input (#148784) Enables the Scribe feature, or Android stylus handwriting text input. ![scribe](https://github.com/flutter/flutter/assets/389558/25a54ae9-9399-4772-8482-913ec7a9b330) This PR only implements basic handwriting input. Other features will be done in subsequent PRs: * https://github.com/flutter/flutter/issues/155948 * https://github.com/flutter/flutter/issues/156018 I created and fixed issue about stylus hovering while working on this: https://github.com/flutter/flutter/issues/148810 Original PR for iOS Scribble, the iOS version of this feature: https://github.com/flutter/flutter/pull/75472 FYI @fbcouch ~~Depends on https://github.com/flutter/engine/pull/52943~~ (merged). Fixes https://github.com/flutter/flutter/issues/115607
Example code I'm using to test this feature (but any TextField works) ```dart import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { final FocusNode _focusNode1 = FocusNode(); final FocusNode _focusNode2 = FocusNode(); final FocusNode _focusNode3 = FocusNode(); final TextEditingController _controller3 = TextEditingController( text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', ); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Scribe demo'), ), body: Center( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 74.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ TextField( focusNode: _focusNode1, autofocus: false, ), TextField( focusNode: _focusNode2, ), TextField( focusNode: _focusNode3, minLines: 4, maxLines: 4, controller: _controller3, ), TextButton( onPressed: () { _focusNode1.unfocus(); _focusNode2.unfocus(); _focusNode3.unfocus(); }, child: const Text('Unfocus'), ), TextButton( onPressed: () { _focusNode1.requestFocus(); SchedulerBinding.instance.addPostFrameCallback((Duration _) { SystemChannels.textInput.invokeMethod('TextInput.hide'); }); }, child: const Text('Focus 1'), ), ], ), ), ), ); } } ```
--------- Co-authored-by: Nate Wilson --- packages/flutter/lib/services.dart | 1 + .../flutter/lib/src/cupertino/text_field.dart | 19 + .../flutter/lib/src/material/text_field.dart | 14 + .../lib/src/material/text_form_field.dart | 6 + packages/flutter/lib/src/services/scribe.dart | 143 ++++ .../lib/src/services/system_channels.dart | 29 + .../flutter/lib/src/services/text_input.dart | 15 +- .../lib/src/widgets/editable_text.dart | 55 +- .../lib/src/widgets/text_selection.dart | 55 +- .../flutter/test/services/scribe_test.dart | 84 +++ .../widgets/editable_text_scribble_test.dart | 686 ++++++++++++++++++ .../widgets/editable_text_scribe_test.dart | 229 ++++++ .../test/widgets/editable_text_test.dart | 658 ----------------- 13 files changed, 1315 insertions(+), 679 deletions(-) create mode 100644 packages/flutter/lib/src/services/scribe.dart create mode 100644 packages/flutter/test/services/scribe_test.dart create mode 100644 packages/flutter/test/widgets/editable_text_scribble_test.dart create mode 100644 packages/flutter/test/widgets/editable_text_scribe_test.dart 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/cupertino/text_field.dart b/packages/flutter/lib/src/cupertino/text_field.dart index 1527397c341..c151a8da504 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)); @@ -1447,6 +1465,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, 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/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 890b4933f44..a7f7337ccdb 100644 --- a/packages/flutter/lib/src/services/text_input.dart +++ b/packages/flutter/lib/src/services/text_input.dart @@ -1066,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, } @@ -1262,9 +1267,13 @@ mixin TextInputClient { void performSelector(String selectorName) {} } -/// An interface to receive focus from the engine. +/// An interface into iOS's stylus hadnwriting text input. /// -/// This is currently only used to handle UIIndirectScribbleInteraction. +/// See also: +/// +/// * [Scribe], which provides similar functionality for Anroid. +/// * [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/widgets/editable_text.dart b/packages/flutter/lib/src/widgets/editable_text.dart index a9f88c1dbba..d99544c4667 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 arbirtrary 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]. /// @@ -1975,6 +2005,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 +2275,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 +2397,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; @@ -4464,7 +4507,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; } @@ -4755,7 +4798,7 @@ class EditableTextState extends State with AutomaticKeepAliveClien @override void insertTextPlaceholder(Size size) { - if (!widget.scribbleEnabled) { + if (!_stylusHandwritingEnabled) { return; } @@ -4770,7 +4813,7 @@ class EditableTextState extends State with AutomaticKeepAliveClien @override void removeTextPlaceholder() { - if (!widget.scribbleEnabled || _placeholderLocation == -1) { + if (!_stylusHandwritingEnabled || _placeholderLocation == -1) { return; } @@ -5284,9 +5327,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/text_selection.dart b/packages/flutter/lib/src/widgets/text_selection.dart index d7087c9bc90..ce92fdcfc6e 100644 --- a/packages/flutter/lib/src/widgets/text_selection.dart +++ b/packages/flutter/lib/src/widgets/text_selection.dart @@ -1857,6 +1857,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 seletion 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 +1892,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 +1908,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 +1920,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 +2260,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 +2285,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/test/services/scribe_test.dart b/packages/flutter/test/services/scribe_test.dart new file mode 100644 index 00000000000..73ad0497b82 --- /dev/null +++ b/packages/flutter/test/services/scribe_test.dart @@ -0,0 +1,84 @@ +// 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/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); + + test('when receiving an unsupported message', () async { + final ByteData? messageBytes = const JSONMessageCodec().encodeMessage({ + '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/widgets/editable_text_scribble_test.dart b/packages/flutter/test/widgets/editable_text_scribble_test.dart new file mode 100644 index 00000000000..384790c8eb8 --- /dev/null +++ b/packages/flutter/test/widgets/editable_text_scribble_test.dart @@ -0,0 +1,686 @@ +// 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] +} 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..9a4dcc467b4 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 { From f7869a47993d49ce640dbd7b719d551a4e00ccf2 Mon Sep 17 00:00:00 2001 From: Jonah Williams Date: Wed, 20 Nov 2024 17:36:55 -0800 Subject: [PATCH 161/386] [flutter_tools] opt iOS/macOS apps out of Metal API validation via migrator, update templates in repo. (#159228) Setting "enableGPUValidationMode = "1"" disables Metal API validation. I know, I know. Fixes https://github.com/flutter/flutter/issues/159227 --- .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + .../xcshareddata/xcschemes/Runner.xcscheme | 1 + packages/flutter_tools/lib/src/ios/mac.dart | 2 + .../metal_api_validation_migration.dart | 50 +++++++ .../lib/src/macos/build_macos.dart | 2 + .../xcschemes/Runner.xcscheme.tmpl | 1 + .../xcschemes/Runner.xcscheme.tmpl | 1 + .../xcschemes/Runner.xcscheme.tmpl | 1 + .../xcschemes/Runner.xcscheme.tmpl | 1 + .../ios/metal_api_validator_test.dart | 132 ++++++++++++++++++ 37 files changed, 219 insertions(+) create mode 100644 packages/flutter_tools/lib/src/ios/migrations/metal_api_validation_migration.dart create mode 100644 packages/flutter_tools/test/general.shard/ios/metal_api_validator_test.dart 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/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"> 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/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/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/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/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/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/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/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/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/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/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/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/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/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_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/packages/flutter_tools/lib/src/ios/mac.dart b/packages/flutter_tools/lib/src/ios/mac.dart index 337afd07dff..5dcc8ec40f8 100644 --- a/packages/flutter_tools/lib/src/ios/mac.dart +++ b/packages/flutter_tools/lib/src/ios/mac.dart @@ -36,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'; @@ -178,6 +179,7 @@ Future buildXcodeProject({ features: featureFlags, ), SwiftPackageManagerGitignoreMigration(project, globals.logger), + MetalAPIValidationMigrator.ios(app.project, globals.logger), ]; final ProjectMigration migration = ProjectMigration(migrators); 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/macos/build_macos.dart b/packages/flutter_tools/lib/src/macos/build_macos.dart index fe78b29af3f..bbda3276f62 100644 --- a/packages/flutter_tools/lib/src/macos/build_macos.dart +++ b/packages/flutter_tools/lib/src/macos/build_macos.dart @@ -15,6 +15,7 @@ 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'; @@ -103,6 +104,7 @@ Future buildMacOS({ features: featureFlags, ), SwiftPackageManagerGitignoreMigration(flutterProject, globals.logger), + MetalAPIValidationMigrator.macos(flutterProject.macos, globals.logger), ]; final ProjectMigration migration = ProjectMigration(migrators); 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/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"> + +'''); + final FakeIosProject project = FakeIosProject(file); + final MetalAPIValidationMigrator validator = MetalAPIValidationMigrator.ios(project, BufferLogger.test()); + + expect(() async => validator.migrate(), returnsNormally); + + expect(file.readAsStringSync(), contains( + 'debugServiceExtension = "internal"' + '\n enableGPUValidationMode = "1"')); + }); + + testWithoutContext('Adds Metal API setting to matching file and crazy indentation', () { + final FileSystem fs = MemoryFileSystem.test(); + + final File file = fs.file('test_file') + ..createSync() + ..writeAsStringSync(''' + + +'''); + final FakeIosProject project = FakeIosProject(file); + final MetalAPIValidationMigrator validator = MetalAPIValidationMigrator.ios(project, BufferLogger.test()); + + expect(() async => validator.migrate(), returnsNormally); + + expect(file.readAsStringSync(), contains( + 'debugServiceExtension = "internal"' + '\n enableGPUValidationMode = "1"')); + }); + + testWithoutContext('Skips modifying file that already references Metal API setting', () { + final FileSystem fs = MemoryFileSystem.test(); + + final File file = fs.file('test_file') + ..createSync() + ..writeAsStringSync(''' + + +'''); + final FakeIosProject project = FakeIosProject(file); + final MetalAPIValidationMigrator validator = MetalAPIValidationMigrator.ios(project, BufferLogger.test()); + + final String initialContents = file.readAsStringSync(); + + expect(() async => validator.migrate(), returnsNormally); + expect(file.readAsStringSync(), initialContents); + }); + + testWithoutContext('No-op on file with no match', () { + final FileSystem fs = MemoryFileSystem.test(); + + final File file = fs.file('does_not_exist') + ..createSync() + ..writeAsStringSync('NO_OP'); + final FakeIosProject project = FakeIosProject(file); + final MetalAPIValidationMigrator validator = MetalAPIValidationMigrator.ios(project, BufferLogger.test()); + + expect(() async => validator.migrate(), returnsNormally); + + expect(file.readAsStringSync(), 'NO_OP'); + }); + + testWithoutContext('No-op on missing file', () async { + final FileSystem fs = MemoryFileSystem.test(); + final FakeIosProject project = FakeIosProject(fs.file('does_not_exist')); + final MetalAPIValidationMigrator validator = MetalAPIValidationMigrator.ios(project, BufferLogger.test()); + + expect(() async => validator.migrate(), returnsNormally); + }); +} + +class FakeIosProject extends Fake implements IosProject { + FakeIosProject(this._file); + + final File _file; + + @override + File xcodeProjectSchemeFile({String? scheme}) { + return _file; + } +} From 1578d7d5f34e2b4eee1db90c5defa43608847775 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Thu, 21 Nov 2024 09:45:09 -0500 Subject: [PATCH 162/386] Roll Flutter Engine from 69c325513a65 to 523d381893c8 (3 revisions) (#159263) https://github.com/flutter/engine/compare/69c325513a65...523d381893c8 2024-11-21 55750689+AthulJoseph27@users.noreply.github.com [Flutter GPU] Added support to set Scissor. (flutter/engine#56302) 2024-11-21 tugorez@users.noreply.github.com Enable view focus (flutter/engine#54966) 2024-11-21 robert.ancell@canonical.com Allow GTK style enum naming (flutter/engine#56731) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index a62ed3d6c22..7a7da45d4cb 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -69c325513a658177fb9b0f743cf9f0cbb1af70f0 +523d381893c871a0f4d851bcd022218f8c4f7879 From 7662e7eae5488fadae66601477f0731fe27a70f9 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Thu, 21 Nov 2024 10:43:59 -0500 Subject: [PATCH 163/386] Roll Packages from e95f6d8fce58 to 913b99ed8542 (7 revisions) (#159268) https://github.com/flutter/packages/compare/e95f6d8fce58...913b99ed8542 2024-11-21 brackenavaron@gmail.com [vector_graphics] handle errors from bytes loader (flutter/packages#8080) 2024-11-21 82763757+derdilla@users.noreply.github.com [flutter_svg] Fix SvgNetworkLoader not closing internal http client (flutter/packages#8126) 2024-11-20 30872003+misos1@users.noreply.github.com [video_player_avfoundation] send video load failure even when eventsink was initialized late (flutter/packages#7194) 2024-11-20 kevmoo@users.noreply.github.com [flutter_markdown] enable Wasm support (flutter/packages#8120) 2024-11-20 98614782+auto-submit[bot]@users.noreply.github.com Reverts "[url_launcher] Add Swift Package Manager integration to example app (#8128)" (flutter/packages#8136) 2024-11-20 737941+loic-sharma@users.noreply.github.com [url_launcher] Add Swift Package Manager integration to example app (flutter/packages#8128) 2024-11-20 stuartmorgan@google.com [pigeon] Enable example app build in CI (flutter/packages#8119) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-packages-flutter-autoroll Please CC flutter-ecosystem@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/flutter_packages.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/flutter_packages.version b/bin/internal/flutter_packages.version index 8ac8998018f..c6b9c3d8b53 100644 --- a/bin/internal/flutter_packages.version +++ b/bin/internal/flutter_packages.version @@ -1 +1 @@ -e95f6d8fce589a6dfbd8ceb6f2ddaa537ec2b2e6 +913b99ed8542052266b260517bde75d549bd629f From 81d2bf5d79348855ef995b9f1f618c443f12fb68 Mon Sep 17 00:00:00 2001 From: jesswrd Date: Thu, 21 Nov 2024 09:49:32 -0600 Subject: [PATCH 164/386] Remove `firebase_abstract_method_smoke_test` (#159145) Deleted Android embedding smoke test `firebase_abstract_method_smoke_test`. It is part of v1 embedding removal cleanup. This test was marked bringup. Fixes https://github.com/flutter/flutter/issues/158212 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- .ci.yaml | 33 --- TESTOWNERS | 1 - .../android/app/build.gradle | 68 ------ .../android/app/src/debug/AndroidManifest.xml | 11 - .../android/app/src/main/AndroidManifest.xml | 44 ---- .../MainActivity.kt | 72 ------ .../main/res/drawable/launch_background.xml | 15 -- .../app/src/main/res/values/styles.xml | 11 - .../app/src/profile/AndroidManifest.xml | 11 - .../android/build.gradle | 34 --- .../android/buildscript-gradle.lockfile | 153 ------------ .../android/gradle.properties | 3 - .../gradle/wrapper/gradle-wrapper.properties | 5 - .../android/project-app.lockfile | 218 ------------------ .../android/project-integration_test.lockfile | 67 ------ .../android/settings.gradle | 41 ---- .../abstract_method_smoke_test/lib/main.dart | 72 ------ .../abstract_method_smoke_test/pubspec.yaml | 22 -- 18 files changed, 881 deletions(-) delete mode 100644 dev/integration_tests/abstract_method_smoke_test/android/app/build.gradle delete mode 100644 dev/integration_tests/abstract_method_smoke_test/android/app/src/debug/AndroidManifest.xml delete mode 100644 dev/integration_tests/abstract_method_smoke_test/android/app/src/main/AndroidManifest.xml delete mode 100644 dev/integration_tests/abstract_method_smoke_test/android/app/src/main/kotlin/com/example/abstract_method_smoke_test/MainActivity.kt delete mode 100644 dev/integration_tests/abstract_method_smoke_test/android/app/src/main/res/drawable/launch_background.xml delete mode 100644 dev/integration_tests/abstract_method_smoke_test/android/app/src/main/res/values/styles.xml delete mode 100644 dev/integration_tests/abstract_method_smoke_test/android/app/src/profile/AndroidManifest.xml delete mode 100644 dev/integration_tests/abstract_method_smoke_test/android/build.gradle delete mode 100644 dev/integration_tests/abstract_method_smoke_test/android/buildscript-gradle.lockfile delete mode 100644 dev/integration_tests/abstract_method_smoke_test/android/gradle.properties delete mode 100644 dev/integration_tests/abstract_method_smoke_test/android/gradle/wrapper/gradle-wrapper.properties delete mode 100644 dev/integration_tests/abstract_method_smoke_test/android/project-app.lockfile delete mode 100644 dev/integration_tests/abstract_method_smoke_test/android/project-integration_test.lockfile delete mode 100644 dev/integration_tests/abstract_method_smoke_test/android/settings.gradle delete mode 100644 dev/integration_tests/abstract_method_smoke_test/lib/main.dart delete mode 100644 dev/integration_tests/abstract_method_smoke_test/pubspec.yaml diff --git a/.ci.yaml b/.ci.yaml index 6f1aa0f924f..1aa37d8e716 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -636,39 +636,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 diff --git a/TESTOWNERS b/TESTOWNERS index 44da941b0f3..5715846e80c 100644 --- a/TESTOWNERS +++ b/TESTOWNERS @@ -315,7 +315,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/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 From 4e03220a8691abdec3a2bc5612afc13c18d966be Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Thu, 21 Nov 2024 11:27:13 -0500 Subject: [PATCH 165/386] Roll Flutter Engine from 523d381893c8 to 78b87f3fe023 (2 revisions) (#159270) https://github.com/flutter/engine/compare/523d381893c8...78b87f3fe023 2024-11-21 mdebbar@google.com [web] Make sure to include all split fonts (flutter/engine#56733) 2024-11-21 mdebbar@google.com [web] Work around wrong pointerId in coalesced events in iOS Safari 18.2 (flutter/engine#56719) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 7a7da45d4cb..cbc33424e6b 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -523d381893c871a0f4d851bcd022218f8c4f7879 +78b87f3fe023b089ef7867425297d506355f4303 From a051be8585769c09beca927e7b58ab3f2fd924d3 Mon Sep 17 00:00:00 2001 From: Elliott Brooks <21270878+elliette@users.noreply.github.com> Date: Thu, 21 Nov 2024 09:12:00 -0800 Subject: [PATCH 166/386] On-device Widget Inspector button exits widget selection (#158219) Fixes https://github.com/flutter/devtools/issues/8155 Previously after enabling Widget Selection mode from DevTools and selecting a widget to inspect, a user would then have to click the on-device "Select widget" button before being able to select another widget. This was very confusing to users; we got multiple comments on our latest DevTools Survey that widget selection mode only worked the first time and was broken on subsequent selections. Now, once "Select widget mode" is enabled from DevTools, any subsequent click is treated as a selection until the user exits from select widget mode either via DevTools or via the Exit Selection mode button. The user can re-position the Exit Selection button to either the left or the right of their device (this way they can select a widget beneath it). ![exit_select_mode_button](https://github.com/user-attachments/assets/e1170753-ade7-4226-baca-8f07667f0587) Note: Previously this button was behind any widget selection overlays. This PR also updates the order of the `Stack` so that exit selection button is on top. --- packages/flutter/lib/src/cupertino/app.dart | 51 ++- packages/flutter/lib/src/material/app.dart | 67 ++- packages/flutter/lib/src/widgets/app.dart | 26 +- .../lib/src/widgets/widget_inspector.dart | 382 ++++++++++++++++-- .../test/widgets/widget_inspector_test.dart | 281 ++++++++++--- 5 files changed, 698 insertions(+), 109 deletions(-) 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/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/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/widget_inspector.dart b/packages/flutter/lib/src/widgets/widget_inspector.dart index 072b94e9209..5e8f9e92d48 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) { @@ -2758,17 +2779,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 +2829,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( @@ -2937,22 +2969,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 +2990,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 +3453,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 +3467,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 +3478,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/test/widgets/widget_inspector_test.dart b/packages/flutter/test/widgets/widget_inspector_test.dart index e4e9c2fb5c7..71a15cbdb7f 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,32 @@ 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), + ); + } + await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( key: inspectorKey, - selectButtonBuilder: selectButtonBuilder, + exitWidgetSelectionButtonBuilder: exitWidgetSelectionButtonBuilder, + moveExitWidgetSelectionButtonBuilder: null, child: Material( child: ListView( children: [ @@ -404,6 +432,7 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { child: const Text('TOP'), ), ElevatedButton( + key: bottomButtonKey, onPressed: () { log.add('bottom'); }, @@ -417,9 +446,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 +460,30 @@ 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 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 +497,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 +519,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 +541,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 +573,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 +590,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 +618,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 +651,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 +693,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 +714,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 +744,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 +759,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 +783,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 +795,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 +818,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 +829,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 +850,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 +885,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'), + ), + ), + ); + + // Intitially 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( @@ -3727,7 +3885,8 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { final Widget widget = Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( - selectButtonBuilder: null, + exitWidgetSelectionButtonBuilder: null, + moveExitWidgetSelectionButtonBuilder: null, child: _applyConstructor(_TrivialWidget.new), ), ); From d1e2c5fba7484a27292256b05c3e000923559688 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Thu, 21 Nov 2024 09:39:13 -0800 Subject: [PATCH 167/386] Try a speculative fix for Gradle OOMs. (#159234) Speculative fix for https://github.com/flutter/flutter/issues/157640. A few observations: - I was a bit paranoid about indented files meaning something was parsed incorrectly - I removed `android.enableR8=true` (not used elsewhere) - I removed `android.experimental.enableNewResourceShrinker=true` (not used elsewhere) - I matched the rest of the `jvmargs` used in the standard template file ... let's hope this does good things? --- ...droid_gradle_flutter_source_path_test.dart | 6 +- .../deferred_components_project.dart | 376 +++++++++--------- 2 files changed, 190 insertions(+), 192 deletions(-) diff --git a/packages/flutter_tools/test/integration.shard/android_gradle_flutter_source_path_test.dart b/packages/flutter_tools/test/integration.shard/android_gradle_flutter_source_path_test.dart index 929cbb022c3..b18a2eb0d11 100644 --- a/packages/flutter_tools/test/integration.shard/android_gradle_flutter_source_path_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_gradle_flutter_source_path_test.dart @@ -49,9 +49,9 @@ void main() { class MissingFlutterSourcePathDeferredComponentsConfig extends BasicDeferredComponentsConfig { final String _flutterSourcePath = ''' - flutter { - source '../..' - } +flutter { + source '../..' +} '''; @override diff --git a/packages/flutter_tools/test/integration.shard/test_data/deferred_components_project.dart b/packages/flutter_tools/test/integration.shard/test_data/deferred_components_project.dart index 665e5200a1e..4fdf43d02e7 100644 --- a/packages/flutter_tools/test/integration.shard/test_data/deferred_components_project.dart +++ b/packages/flutter_tools/test/integration.shard/test_data/deferred_components_project.dart @@ -11,60 +11,60 @@ class DeferredComponentsProject extends Project { @override final String pubspec = ''' - name: test - environment: - sdk: '>=3.2.0-0 <4.0.0' +name: test +environment: + sdk: '>=3.2.0-0 <4.0.0' - dependencies: - flutter: - sdk: flutter +dependencies: flutter: - assets: - - test_assets/asset1.txt - deferred-components: - - name: component1 - libraries: - - package:test/deferred_library.dart - assets: - - test_assets/asset2.txt - '''; + sdk: flutter +flutter: + assets: + - test_assets/asset1.txt + deferred-components: + - name: component1 + libraries: + - package:test/deferred_library.dart + assets: + - test_assets/asset2.txt +'''; @override final String main = r''' - import 'dart:async'; +import 'dart:async'; - import 'package:flutter/material.dart'; - import 'deferred_library.dart' deferred as DeferredLibrary; +import 'package:flutter/material.dart'; +import 'deferred_library.dart' deferred as DeferredLibrary; - Future? libFuture; - String deferredText = 'incomplete'; +Future? libFuture; +String deferredText = 'incomplete'; - Future main() async { - while (true) { - if (libFuture == null) { - libFuture = DeferredLibrary.loadLibrary(); - libFuture?.whenComplete(() => deferredText = 'complete ${DeferredLibrary.add(10, 42)}'); - } - runApp(MyApp()); - await Future.delayed(const Duration(milliseconds: 50)); +Future main() async { + while (true) { + if (libFuture == null) { + libFuture = DeferredLibrary.loadLibrary(); + libFuture?.whenComplete(() => deferredText = 'complete ${DeferredLibrary.add(10, 42)}'); } + runApp(MyApp()); + await Future.delayed(const Duration(milliseconds: 50)); } +} - class MyApp extends StatelessWidget { - @override - Widget build(BuildContext context) { - topLevelFunction(); - return MaterialApp( // BUILD BREAKPOINT - title: 'Flutter Demo', - home: Container(), - ); - } +class MyApp extends StatelessWidget { + @override + Widget build(BuildContext context) { + topLevelFunction(); + return MaterialApp( // BUILD BREAKPOINT + title: 'Flutter Demo', + home: Container(), + ); } +} - topLevelFunction() { - print(deferredText); // TOP LEVEL BREAKPOINT - } - '''; +topLevelFunction() { + print(deferredText); // TOP LEVEL BREAKPOINT +} +'''; @override final DeferredComponentsConfig deferredComponents; @@ -74,188 +74,186 @@ class DeferredComponentsProject extends Project { class BasicDeferredComponentsConfig extends DeferredComponentsConfig { @override String get deferredLibrary => r''' - library DeferredLibrary; +library DeferredLibrary; - int add(int i, int j) { - return i + j; - } - '''; +int add(int i, int j) { + return i + j; +} +'''; @override String? get deferredComponentsGolden => r''' - loading-units: - - id: 2 - libraries: - - package:test/deferred_library.dart - '''; +loading-units: + - id: 2 + libraries: + - package:test/deferred_library.dart +'''; - @override - String get androidSettings => r''' - include ':app', ':component1' +@override +String get androidSettings => r''' +include ':app', ':component1' - def localPropertiesFile = new File(rootProject.projectDir, "local.properties") - def properties = new Properties() +def localPropertiesFile = new File(rootProject.projectDir, "local.properties") +def properties = new Properties() - assert localPropertiesFile.exists() - localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } +assert localPropertiesFile.exists() +localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } - def flutterSdkPath = properties.getProperty("flutter.sdk") - assert flutterSdkPath != null, "flutter.sdk not set in local.properties" - apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" - '''; +def flutterSdkPath = properties.getProperty("flutter.sdk") +assert flutterSdkPath != null, "flutter.sdk not set in local.properties" +apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" +'''; - @override - String get androidBuild => r''' - buildscript { - ext.kotlin_version = '1.8.22' - repositories { - google() - mavenCentral() - } +@override +String get androidBuild => r''' +buildscript { + ext.kotlin_version = '1.8.22' + repositories { + google() + mavenCentral() + } - dependencies { - classpath 'com.android.tools.build:gradle:8.1.0' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } - } + dependencies { + classpath 'com.android.tools.build:gradle:8.1.0' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} - allprojects { - repositories { - google() - mavenCentral() - } - } +allprojects { + repositories { + google() + mavenCentral() + } +} - rootProject.layout.buildDirectory.value(rootProject.layout.buildDirectory.dir("../../build").get()) - subprojects { - project.layout.buildDirectory.value(rootProject.layout.buildDirectory.dir(project.name).get()) - } - subprojects { - project.evaluationDependsOn(':app') - } +rootProject.layout.buildDirectory.value(rootProject.layout.buildDirectory.dir("../../build").get()) +subprojects { + project.layout.buildDirectory.value(rootProject.layout.buildDirectory.dir(project.name).get()) +} +subprojects { + project.evaluationDependsOn(':app') +} - tasks.register("clean", Delete) { - delete rootProject.layout.buildDirectory - } - '''; +tasks.register("clean", Delete) { + delete rootProject.layout.buildDirectory +} +'''; @override String get appBuild => r''' - def localProperties = new Properties() - def localPropertiesFile = rootProject.file('local.properties') - if (localPropertiesFile.exists()) { - localPropertiesFile.withReader('UTF-8') { reader -> - localProperties.load(reader) - } - } +def localProperties = new Properties() +def localPropertiesFile = rootProject.file('local.properties') +if (localPropertiesFile.exists()) { + localPropertiesFile.withReader('UTF-8') { reader -> + localProperties.load(reader) + } +} - def flutterRoot = localProperties.getProperty('flutter.sdk') - if (flutterRoot == null) { - throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") - } +def flutterRoot = localProperties.getProperty('flutter.sdk') +if (flutterRoot == null) { + throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") +} - def flutterVersionCode = localProperties.getProperty('flutter.versionCode') - if (flutterVersionCode == null) { - flutterVersionCode = '1' - } +def flutterVersionCode = localProperties.getProperty('flutter.versionCode') +if (flutterVersionCode == null) { + flutterVersionCode = '1' +} - def flutterVersionName = localProperties.getProperty('flutter.versionName') - if (flutterVersionName == null) { - flutterVersionName = '1.0' - } +def flutterVersionName = localProperties.getProperty('flutter.versionName') +if (flutterVersionName == null) { + flutterVersionName = '1.0' +} - def keystoreProperties = new Properties() - def keystorePropertiesFile = rootProject.file('key.properties') - if (keystorePropertiesFile.exists()) { - keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) - } +def keystoreProperties = new Properties() +def keystorePropertiesFile = rootProject.file('key.properties') +if (keystorePropertiesFile.exists()) { + keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) +} - apply plugin: 'com.android.application' - apply plugin: 'kotlin-android' - apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' +apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" - android { - namespace = "com.example.splitaot" - compileSdk flutter.compileSdkVersion - ndkVersion flutter.ndkVersion +android { + namespace = "com.example.splitaot" + compileSdk flutter.compileSdkVersion + ndkVersion flutter.ndkVersion - compileOptions { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 - } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } - kotlinOptions { - jvmTarget = JavaVersion.VERSION_1_8 - } + kotlinOptions { + jvmTarget = JavaVersion.VERSION_1_8 + } - sourceSets { - main.java.srcDirs += 'src/main/kotlin' - } + sourceSets { + main.java.srcDirs += 'src/main/kotlin' + } - lintOptions { - disable 'InvalidPackage' - } + lintOptions { + disable 'InvalidPackage' + } - defaultConfig { - // Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). - applicationId "ninja.qian.splitaottest1" - minSdkVersion flutter.minSdkVersion - targetSdkVersion flutter.targetSdkVersion - versionCode flutterVersionCode.toInteger() - versionName flutterVersionName - } - signingConfigs { - release { - keyAlias keystoreProperties['keyAlias'] - keyPassword keystoreProperties['keyPassword'] - storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null - storePassword keystoreProperties['storePassword'] - } - } - buildTypes { - release { - // Add your own signing config for the release build. - // Signing with the debug keys for now, so `flutter run --release` works. - signingConfig signingConfigs.release - } - } - } + defaultConfig { + // Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId "ninja.qian.splitaottest1" + minSdkVersion flutter.minSdkVersion + targetSdkVersion flutter.targetSdkVersion + versionCode flutterVersionCode.toInteger() + versionName flutterVersionName + } + signingConfigs { + release { + keyAlias keystoreProperties['keyAlias'] + keyPassword keystoreProperties['keyPassword'] + storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null + storePassword keystoreProperties['storePassword'] + } + } + buildTypes { + release { + // Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig signingConfigs.release + } + } +} - flutter { - source '../..' - } +flutter { + source '../..' +} - dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" - implementation "com.google.android.play:core:1.8.0" - } +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + implementation "com.google.android.play:core:1.8.0" +} - '''; +'''; @override String get androidLocalProperties => ''' - flutter.sdk=${getFlutterRoot()} - flutter.buildMode=release - flutter.versionName=1.0.0 - flutter.versionCode=22 - '''; +flutter.sdk=${getFlutterRoot()} +flutter.buildMode=release +flutter.versionName=1.0.0 +flutter.versionCode=22 +'''; @override String get androidGradleProperties => ''' - org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=2G -XX:+HeapDumpOnOutOfMemoryError - android.useAndroidX=true - android.enableJetifier=true - android.enableR8=true - android.experimental.enableNewResourceShrinker=true - '''; +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +android.enableJetifier=true +'''; @override String get androidKeyProperties => ''' - storePassword=123456 - keyPassword=123456 - keyAlias=test_release_key - storeFile=key.jks - '''; +storePassword=123456 +keyPassword=123456 +keyAlias=test_release_key +storeFile=key.jks +'''; // This is a test jks keystore, generated for testing use only. Do not use this key in an actual // application. @@ -611,9 +609,9 @@ class NoGoldenDeferredComponentsConfig extends BasicDeferredComponentsConfig { class MismatchedGoldenDeferredComponentsConfig extends BasicDeferredComponentsConfig { @override String get deferredComponentsGolden => r''' - loading-units: - - id: 2 - libraries: - - package:test/invalid_lib_name.dart - '''; +loading-units: + - id: 2 + libraries: + - package:test/invalid_lib_name.dart +'''; } From c7dd6419d9adb465c0ecedaee5d35fe58480a17a Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Thu, 21 Nov 2024 09:50:46 -0800 Subject: [PATCH 168/386] Remove `RepaintBoundary` that is no longer needed. (#159232) Closes https://github.com/flutter/flutter/issues/66006. From what I can tell in the multi-view effort a variation of https://github.com/flutter/flutter/pull/88609 already landed, meaning that the current device-pixel-ratio is being used (as the tests in #88609 are now passing), and I believe that means we can remove the override/hack. Will rely on "Google Testing" to run a TGP internally, or do so myself if necessary. --- packages/flutter_test/test/bindings_test.dart | 5 +++++ packages/integration_test/lib/integration_test.dart | 8 -------- packages/integration_test/test/binding_test.dart | 6 +++--- 3 files changed, 8 insertions(+), 11 deletions(-) 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/integration_test/lib/integration_test.dart b/packages/integration_test/lib/integration_test.dart index e6ef99088b1..de9f4728233 100644 --- a/packages/integration_test/lib/integration_test.dart +++ b/packages/integration_test/lib/integration_test.dart @@ -446,14 +446,6 @@ https://docs.flutter.dev/testing/integration-tests @override Timeout defaultTestTimeout = Timeout.none; - @override - Widget wrapWithDefaultView(Widget rootWidget) { - // This is a workaround where screenshots of root widgets have incorrect - // bounds. - // TODO(jiahaog): Remove when https://github.com/flutter/flutter/issues/66006 is fixed. - return super.wrapWithDefaultView(RepaintBoundary(child: rootWidget)); - } - @override void reportExceptionNoticed(FlutterErrorDetails exception) { // This method is called to log errors as they happen, and they will also diff --git a/packages/integration_test/test/binding_test.dart b/packages/integration_test/test/binding_test.dart index 13163221312..28fafe41c0d 100644 --- a/packages/integration_test/test/binding_test.dart +++ b/packages/integration_test/test/binding_test.dart @@ -124,11 +124,11 @@ Future main() async { }); }); - // TODO(jiahaog): Remove when https://github.com/flutter/flutter/issues/66006 is fixed. - testWidgets('root widgets are wrapped with a RepaintBoundary', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/66006. + testWidgets('root view reports correct dimensions', (WidgetTester tester) async { await tester.pumpWidget(const Placeholder()); - expect(find.byType(RepaintBoundary), findsOneWidget); + expect(tester.binding.renderView.paintBounds, const Rect.fromLTWH(0, 0, 2400, 1800)); }); testWidgets('integration test has no label', (WidgetTester tester) async { From efe8737ea0a26d73dbbbe87b0a7da00b77ee5fbf Mon Sep 17 00:00:00 2001 From: Jason Simmons Date: Thu, 21 Nov 2024 09:53:57 -0800 Subject: [PATCH 169/386] Shut down DevTools and DDS processes if flutter_tools is killed by a signal (#159238) See https://github.com/flutter/flutter/issues/159154 --- .../lib/src/resident_devtools_handler.dart | 4 +--- packages/flutter_tools/lib/src/run_hot.dart | 2 ++ .../flutter_tools/test/general.shard/hot_shared.dart | 10 +++++++--- .../flutter_tools/test/general.shard/run_hot_test.dart | 4 ++++ 4 files changed, 14 insertions(+), 6 deletions(-) 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/run_hot.dart b/packages/flutter_tools/lib/src/run_hot.dart index 1f8d040ca7c..3d737c5913c 100644 --- a/packages/flutter_tools/lib/src/run_hot.dart +++ b/packages/flutter_tools/lib/src/run_hot.dart @@ -1248,8 +1248,10 @@ class HotRunner extends ResidentRunner { @override Future cleanupAfterSignal() async { + await residentDevtoolsHandler!.shutdown(); await stopEchoingDeviceLog(); await hotRunnerConfig!.runPreShutdownOperations(); + shutdownDartDevelopmentService(); if (stopAppDuringCleanup) { return exitApp(); } diff --git a/packages/flutter_tools/test/general.shard/hot_shared.dart b/packages/flutter_tools/test/general.shard/hot_shared.dart index 5a1bda9d231..7b878c10691 100644 --- a/packages/flutter_tools/test/general.shard/hot_shared.dart +++ b/packages/flutter_tools/test/general.shard/hot_shared.dart @@ -54,7 +54,7 @@ class FakeDevice extends Fake implements Device { bool disposed = false; @override - final DartDevelopmentService dds = _FakeDartDevelopmentService(); + final DartDevelopmentService dds = FakeDartDevelopmentService(); @override bool isSupported() => true; @@ -94,9 +94,13 @@ class FakeDevice extends Fake implements Device { } } -class _FakeDartDevelopmentService extends Fake implements DartDevelopmentService { +class FakeDartDevelopmentService extends Fake implements DartDevelopmentService { + bool wasShutdown = false; + @override - void shutdown() {} + void shutdown() { + wasShutdown = true; + } } class FakeFlutterDevice extends Fake implements FlutterDevice { diff --git a/packages/flutter_tools/test/general.shard/run_hot_test.dart b/packages/flutter_tools/test/general.shard/run_hot_test.dart index d1394c1a3ef..c53ba116481 100644 --- a/packages/flutter_tools/test/general.shard/run_hot_test.dart +++ b/packages/flutter_tools/test/general.shard/run_hot_test.dart @@ -9,6 +9,7 @@ import 'package:flutter_tools/src/compile.dart'; import 'package:flutter_tools/src/devfs.dart'; import 'package:flutter_tools/src/device.dart'; import 'package:flutter_tools/src/reporting/reporting.dart'; +import 'package:flutter_tools/src/resident_devtools_handler.dart'; import 'package:flutter_tools/src/resident_runner.dart'; import 'package:flutter_tools/src/run_hot.dart'; import 'package:flutter_tools/src/vmservice.dart'; @@ -56,11 +57,14 @@ void main() { target: 'main.dart', debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), analytics: _FakeAnalytics(), + devtoolsHandler: createNoOpHandler, ); await runner.run(); await runner.cleanupAfterSignal(); expect(flutterDevice.wasExited, true); + expect((flutterDevice.device.dds as FakeDartDevelopmentService).wasShutdown, true); + expect((runner.residentDevtoolsHandler! as NoOpDevtoolsHandler).wasShutdown, true); }, overrides: { FileSystem: () => fileSystem, From 399403ae6a389fec8d2187850117218d14a6258e Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Thu, 21 Nov 2024 12:54:56 -0500 Subject: [PATCH 170/386] Roll Flutter Engine from 78b87f3fe023 to d1a08064e193 (1 revision) (#159280) https://github.com/flutter/engine/compare/78b87f3fe023...d1a08064e193 2024-11-21 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from oq6Ztlu1b1mgdDSPH... to zhFzwYCH-N_wasTnM... (flutter/engine#56736) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from oq6Ztlu1b1mg to zhFzwYCH-N_w If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index cbc33424e6b..d84d89a76f5 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -78b87f3fe023b089ef7867425297d506355f4303 +d1a08064e193e7b1ea672505bb4734de8a1cb439 diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index 5cb06ba673b..88f94ccb72f 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -oq6Ztlu1b1mgdDSPHcGPu9oR19woqUEXinAJnHoE6scC +zhFzwYCH-N_wasTnMUjFf2dzRXRIMjNPuX6LDgic7oAC From 93d772c5cdd8399de64daa83169f4f964c4e01b2 Mon Sep 17 00:00:00 2001 From: Ben Konyi Date: Thu, 21 Nov 2024 13:33:15 -0500 Subject: [PATCH 171/386] Added additional logging to `_listCoreDevices` (#159275) Attempting to collect additional context into the failure outlined in https://github.com/flutter/flutter/issues/141892 --- packages/flutter_tools/lib/src/ios/core_devices.dart | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/flutter_tools/lib/src/ios/core_devices.dart b/packages/flutter_tools/lib/src/ios/core_devices.dart index 2ccbb21a6a9..fb851550cd8 100644 --- a/packages/flutter_tools/lib/src/ios/core_devices.dart +++ b/packages/flutter_tools/lib/src/ios/core_devices.dart @@ -94,6 +94,10 @@ class IOSCoreDeviceControl { _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()}'); + _logger.printError('Using file system type: ${_fileSystem.runtimeType}'); + if (_fileSystem is LocalFileSystem) { + _logger.printError('LocalFileSystem disposed: ${_fileSystem.disposed}'); + } throw StateError('Expected the file ${output.path} to exist but it did not'); } else if (isToolPossiblyShutdown) { return []; From d7f5547ecd036d80f408935e4dc154a0dbe0b8d8 Mon Sep 17 00:00:00 2001 From: Jason Simmons Date: Thu, 21 Nov 2024 11:04:06 -0800 Subject: [PATCH 172/386] Do a clean shutdown of the flutter_tools processes started by observatory_port_test (#159169) Killing the flutter_tools parent process may leak child processes spawned by the tools. Also wait for the message indicating that DevTools has started before stopping flutter_tools. If DevTools has not fully launched, then there may be a race between DevTools startup and flutter_tools shutdown. Fixes https://github.com/flutter/flutter/issues/159154 --- .../test/integration.shard/observatory_port_test.dart | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/flutter_tools/test/integration.shard/observatory_port_test.dart b/packages/flutter_tools/test/integration.shard/observatory_port_test.dart index eb143e2f85b..1ae471f7270 100644 --- a/packages/flutter_tools/test/integration.shard/observatory_port_test.dart +++ b/packages/flutter_tools/test/integration.shard/observatory_port_test.dart @@ -26,7 +26,7 @@ Future waitForVmServiceMessage(Process process, int port) async { .transform(utf8.decoder) .listen((String line) { printOnFailure(line); - if (line.contains('A Dart VM Service on Flutter test device is available at')) { + if (line.contains('The Flutter DevTools debugger and profiler on Flutter test device is available at')) { if (line.contains('http://127.0.0.1:$port')) { completer.complete(); } else { @@ -66,7 +66,9 @@ void main() { 'flutter-tester', ], workingDirectory: tempDir.path); await waitForVmServiceMessage(process, port); - process.kill(); + // Send a quit command to flutter_tools to cleanly shut down the tool + // and its child processes. + process.stdin.writeln('q'); await process.exitCode; }); @@ -88,7 +90,7 @@ void main() { 'flutter-tester', ], workingDirectory: tempDir.path); await waitForVmServiceMessage(process, ddsPort); - process.kill(); + process.stdin.writeln('q'); await process.exitCode; }); @@ -105,7 +107,7 @@ void main() { 'flutter-tester', ], workingDirectory: tempDir.path); await waitForVmServiceMessage(process, ddsPort); - process.kill(); + process.stdin.writeln('q'); await process.exitCode; }); From 728cedc62a795efa6eadd45a3a5d194fcd76023e Mon Sep 17 00:00:00 2001 From: Dominik Toton <166132265+dtscalac@users.noreply.github.com> Date: Thu, 21 Nov 2024 21:40:11 +0100 Subject: [PATCH 173/386] Fix `--web-header` flag for `flutter drive` (#159039) This PR makes sure that `--web-header` flag works together with the `flutter drive` command. Currently the flag is correctly parsed but it is not properly propagated and ends up being unused when running the web server for tests. I have validated the fix by following the steps to reproduce from: https://github.com/flutter/flutter/issues/159037. #### Before the fix No custom HTTP header in test run: ![Screenshot 2024-11-16 at 22 21 36](https://github.com/user-attachments/assets/b3d4e34b-fe2b-4d32-8b0a-2d55e5d23f69) #### After the fix Correct HTTP headers in test run: ![Screenshot 2024-11-16 at 22 13 43](https://github.com/user-attachments/assets/b74a41de-69c5-4968-82c0-a08d29a3252d) Fixes #159037 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- .../lib/src/drive/web_driver_service.dart | 2 ++ .../drive/web_driver_service_test.dart | 17 ++++++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) 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 8958a4150b7..a0b5c7296a4 100644 --- a/packages/flutter_tools/lib/src/drive/web_driver_service.dart +++ b/packages/flutter_tools/lib/src/drive/web_driver_service.dart @@ -78,6 +78,7 @@ class WebDriverService extends DriverService { hostname: debuggingOptions.hostname, webRenderer: debuggingOptions.webRenderer, webUseWasm: debuggingOptions.webUseWasm, + webHeaders: debuggingOptions.webHeaders, ) : DebuggingOptions.enabled( buildInfo, @@ -86,6 +87,7 @@ class WebDriverService extends DriverService { disablePortPublication: debuggingOptions.disablePortPublication, webRenderer: debuggingOptions.webRenderer, webUseWasm: debuggingOptions.webUseWasm, + webHeaders: debuggingOptions.webHeaders, ), stayResident: true, flutterProject: FlutterProject.current(), diff --git a/packages/flutter_tools/test/general.shard/drive/web_driver_service_test.dart b/packages/flutter_tools/test/general.shard/drive/web_driver_service_test.dart index 8854e2c7a62..9d08262a096 100644 --- a/packages/flutter_tools/test/general.shard/drive/web_driver_service_test.dart +++ b/packages/flutter_tools/test/general.shard/drive/web_driver_service_test.dart @@ -270,6 +270,17 @@ void main() { WebRunnerFactory: () => FakeWebRunnerFactory(), }); + testUsingContext('WebDriverService starts an app with provided web headers', () async { + final WebDriverService service = setUpDriverService(); + final FakeDevice device = FakeDevice(); + final Map webHeaders = {'test-header': 'test-value'}; + await service.start(BuildInfo.profile, device, DebuggingOptions.enabled(BuildInfo.profile, webHeaders: webHeaders, ipv6: true)); + await service.stop(); + expect(FakeResidentRunner.instance.debuggingOptions.webHeaders, equals(webHeaders)); + }, overrides: { + WebRunnerFactory: () => FakeWebRunnerFactory(), + }); + testUsingContext('WebDriverService will throw when an invalid launch url is provided', () async { final WebDriverService service = setUpDriverService(); final FakeDevice device = FakeDevice(); @@ -310,7 +321,7 @@ class FakeWebRunnerFactory implements WebRunnerFactory { bool? stayResident, FlutterProject? flutterProject, bool? ipv6, - DebuggingOptions? debuggingOptions, + required DebuggingOptions debuggingOptions, UrlTunneller? urlTunneller, Logger? logger, FileSystem? fileSystem, @@ -322,6 +333,7 @@ class FakeWebRunnerFactory implements WebRunnerFactory { expect(stayResident, isTrue); return FakeResidentRunner( doResolveToError: doResolveToError, + debuggingOptions: debuggingOptions, ); } } @@ -329,6 +341,7 @@ class FakeWebRunnerFactory implements WebRunnerFactory { class FakeResidentRunner extends Fake implements ResidentRunner { FakeResidentRunner({ required this.doResolveToError, + required this.debuggingOptions, }) { instance = this; } @@ -336,6 +349,8 @@ class FakeResidentRunner extends Fake implements ResidentRunner { static late FakeResidentRunner instance; final bool doResolveToError; + @override + final DebuggingOptions debuggingOptions; final Completer _exitCompleter = Completer(); final List callLog = []; From afb0ac9b5078250035681897b1daef0be1971eaf Mon Sep 17 00:00:00 2001 From: Zachary Anderson Date: Fri, 22 Nov 2024 09:21:05 -0800 Subject: [PATCH 174/386] Move Linux packages_autoroller to bringup (#159336) For https://github.com/flutter/flutter/issues/159316 --- .ci.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.ci.yaml b/.ci.yaml index 1aa37d8e716..a9842eb91eb 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -392,6 +392,7 @@ targets: - name: Linux packages_autoroller presubmit: false + bringup: true # https://github.com/flutter/flutter/issues/159316 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 From 6fbfed888170205e7fa0471b3a11fb4d8a84ddd6 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Fri, 22 Nov 2024 12:26:16 -0500 Subject: [PATCH 175/386] Roll Flutter Engine from d1a08064e193 to 6f941c961b05 (5 revisions) (#159308) https://github.com/flutter/engine/compare/d1a08064e193...6f941c961b05 2024-11-21 98614782+auto-submit[bot]@users.noreply.github.com Reverts "[Impeller] support GLES 3.0 MSAA without extension. (#56705)" (flutter/engine#56741) 2024-11-21 skia-flutter-autoroll@skia.org Roll Dart SDK from dde57dc75c15 to b36e4d731d67 (1 revision) (flutter/engine#56723) 2024-11-21 dacoharkes@google.com [native assets] Consume `NativeAssetsManifest.json` (flutter/engine#56727) 2024-11-21 jonahwilliams@google.com [Impeller] support GLES 3.0 MSAA without extension. (flutter/engine#56705) 2024-11-21 30870216+gaaclarke@users.noreply.github.com Updated some impeller benchmark urls (flutter/engine#56721) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index d84d89a76f5..5fff410b1d8 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -d1a08064e193e7b1ea672505bb4734de8a1cb439 +6f941c961b05eebbe3cff2febb3bd91d6a02c87b From 793569f621f79119dd7cb2c82c403b5d52271946 Mon Sep 17 00:00:00 2001 From: Lam Thanh Nhan Date: Sat, 23 Nov 2024 00:34:00 +0700 Subject: [PATCH 176/386] Add `columnWidth` Property to `DataTable` for Customizable Column Widths (#159279) After discussing with @Hixie in #51799, this PR has been created to implement the ability to customize column widths in DataTable. This change introduces the `columnWidth` property to `DataColumn`, allowing developers to specify column widths using `TableColumnWidth` within a `DataTable`. ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [ ] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- .../flutter/lib/src/material/data_table.dart | 22 ++++- .../test/material/data_table_test.dart | 86 +++++++++++++++++++ 2 files changed, 107 insertions(+), 1 deletion(-) 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/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) { From a77aad7517ab2c50535d7fd3462c63f02de1bfca Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Fri, 22 Nov 2024 13:21:43 -0500 Subject: [PATCH 177/386] Roll Packages from 913b99ed8542 to 920321356e45 (9 revisions) (#159338) https://github.com/flutter/packages/compare/913b99ed8542...920321356e45 2024-11-22 737941+loic-sharma@users.noreply.github.com Reland "[url_launcher] Add Swift Package Manager integration to example app" (flutter/packages#8148) 2024-11-22 meliksahcakirr@gmail.com [webview_flutter_wkwebview] Webkit webview controller multiple registration fix (flutter/packages#8078) 2024-11-22 1341156974@qq.com [quick_actions_plaform_interface] add localizedSubtitle (flutter/packages#8112) 2024-11-22 737941+loic-sharma@users.noreply.github.com [tools] Don't check license of generated Swift package (flutter/packages#8137) 2024-11-21 engine-flutter-autoroll@skia.org Roll Flutter from 8536b96ebb3e to 93d772c5cdd8 (37 revisions) (flutter/packages#8147) 2024-11-21 omar_hanafy@icloud.com [go_router] Fix: Consistent PopScope Handling on Root Routes issue #140869 (flutter/packages#8045) 2024-11-21 louisehsu@google.com [in_app_purchase_storekit] fix price displayed with wrong precision (flutter/packages#8127) 2024-11-21 10687576+bparrishMines@users.noreply.github.com [pigeon] Removes the `@protected` annotation from the InstanceManager field of the `PigeonInternalProxyApiBaseClass` (flutter/packages#8125) 2024-11-21 stuartmorgan@google.com [google_maps_flutter] Use structured Pigeon data on iOS (flutter/packages#8142) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-packages-flutter-autoroll Please CC flutter-ecosystem@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/flutter_packages.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/flutter_packages.version b/bin/internal/flutter_packages.version index c6b9c3d8b53..f5fbdfef09e 100644 --- a/bin/internal/flutter_packages.version +++ b/bin/internal/flutter_packages.version @@ -1 +1 @@ -913b99ed8542052266b260517bde75d549bd629f +920321356e4507f1471bb00413d84b846a3c2697 From e21db87817f730eaa6198550e0522fbc2ad99cac Mon Sep 17 00:00:00 2001 From: Taha Tesser Date: Fri, 22 Nov 2024 20:42:57 +0200 Subject: [PATCH 178/386] Introduce `CircularProgressIndicator.padding` for the updated M3 specs (#159271) Fix [Add `CircularProgressIndicator` padding to match M3 specs](https://github.com/flutter/flutter/issues/159267) ### Code sample
expand to view the code sample ```dart import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( body: Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( width: 40, height: 40, color: Colors.red, alignment: Alignment.center, child: const Text( '40x40px', style: TextStyle(fontSize: 8, color: Colors.white), ), ), const ColoredBox( color: Colors.amber, child: CircularProgressIndicator( year2023: false, value: 0.4, ), ), Container( width: 48, height: 48, color: Colors.red, alignment: Alignment.center, child: const Text( '48x48px', style: TextStyle(fontSize: 10, color: Colors.white), ), ) ], ), ), ), ); } } ```
### Preview Screenshot 2024-11-21 at 17 13 25 ### Specs ![Screenshot_2024-11-20_at_12 17 46_PM](https://github.com/user-attachments/assets/3ab005cc-e93a-485a-8470-f80072440948) ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [ ] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- .../lib/progress_indicator_template.dart | 7 +- .../lib/src/material/progress_indicator.dart | 67 +++++++++++++------ .../material/progress_indicator_theme.dart | 12 +++- .../material/progress_indicator_test.dart | 59 ++++++++++++++-- .../progress_indicator_theme_test.dart | 23 ++++++- 5 files changed, 136 insertions(+), 32 deletions(-) diff --git a/dev/tools/gen_defaults/lib/progress_indicator_template.dart b/dev/tools/gen_defaults/lib/progress_indicator_template.dart index d7a1effaefc..8c04d76a198 100644 --- a/dev/tools/gen_defaults/lib/progress_indicator_template.dart +++ b/dev/tools/gen_defaults/lib/progress_indicator_template.dart @@ -32,12 +32,15 @@ class _Circular${blockName}DefaultsM3 extends ProgressIndicatorThemeData { @override BoxConstraints get constraints => const BoxConstraints( - minWidth: 48.0, - minHeight: 48.0, + 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/packages/flutter/lib/src/material/progress_indicator.dart b/packages/flutter/lib/src/material/progress_indicator.dart index c8fd9aef7cb..b92922244bf 100644 --- a/packages/flutter/lib/src/material/progress_indicator.dart +++ b/packages/flutter/lib/src/material/progress_indicator.dart @@ -745,6 +745,7 @@ class CircularProgressIndicator extends ProgressIndicator { 'This feature was deprecated after v3.27.0-0.1.pre.' ) this.year2023 = true, + this.padding, }) : _indicatorType = _ActivityIndicatorType.material; /// Creates an adaptive progress indicator that is a @@ -774,6 +775,7 @@ class CircularProgressIndicator extends ProgressIndicator { 'This feature was deprecated after v3.27.0-0.2.pre.' ) this.year2023 = true, + this.padding, }) : _indicatorType = _ActivityIndicatorType.adaptive; final _ActivityIndicatorType _indicatorType; @@ -854,6 +856,13 @@ class CircularProgressIndicator extends ProgressIndicator { ) 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]. @@ -967,28 +976,41 @@ class _CircularProgressIndicatorState extends State w : widget.trackGap ?? indicatorTheme.trackGap ?? defaults.trackGap; - return widget._buildSemanticsWrapper( - context: context, - child: 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: widget.year2023, - ), + 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: widget.year2023, ), ), ); + + if (effectivePadding != null) { + result = Padding( + padding: effectivePadding, + child: result, + ); + } + + return widget._buildSemanticsWrapper( + context: context, + child: result, + ); } Widget _buildAnimation() { @@ -1396,12 +1418,15 @@ class _CircularProgressIndicatorDefaultsM3 extends ProgressIndicatorThemeData { @override BoxConstraints get constraints => const BoxConstraints( - minWidth: 48.0, - minHeight: 48.0, + 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 31df16a02ba..2a6f7f4eb2d 100644 --- a/packages/flutter/lib/src/material/progress_indicator_theme.dart +++ b/packages/flutter/lib/src/material/progress_indicator_theme.dart @@ -47,6 +47,7 @@ class ProgressIndicatorThemeData with Diagnosticable { this.strokeCap, this.constraints, this.trackGap, + this.circularTrackPadding, }); /// The color of the [ProgressIndicator]'s indicator. @@ -110,6 +111,9 @@ class ProgressIndicatorThemeData with Diagnosticable { /// is false, then no track gap will be drawn. final double? trackGap; + /// Overrides the padding of the [CircularProgressIndicator]. + final EdgeInsetsGeometry? circularTrackPadding; + /// Creates a copy of this object but with the given fields replaced with the /// new values. ProgressIndicatorThemeData copyWith({ @@ -126,6 +130,7 @@ class ProgressIndicatorThemeData with Diagnosticable { StrokeCap? strokeCap, BoxConstraints? constraints, double? trackGap, + EdgeInsetsGeometry? circularTrackPadding, }) { return ProgressIndicatorThemeData( color: color ?? this.color, @@ -141,6 +146,7 @@ class ProgressIndicatorThemeData with Diagnosticable { strokeCap : strokeCap ?? this.strokeCap, constraints: constraints ?? this.constraints, trackGap : trackGap ?? this.trackGap, + circularTrackPadding: circularTrackPadding ?? this.circularTrackPadding, ); } @@ -165,6 +171,7 @@ class ProgressIndicatorThemeData with Diagnosticable { 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), ); } @@ -183,6 +190,7 @@ class ProgressIndicatorThemeData with Diagnosticable { strokeCap, constraints, trackGap, + circularTrackPadding, ); @override @@ -206,7 +214,8 @@ class ProgressIndicatorThemeData with Diagnosticable { && other.strokeWidth == strokeWidth && other.strokeCap == strokeCap && other.constraints == constraints - && other.trackGap == trackGap; + && other.trackGap == trackGap + && other.circularTrackPadding == circularTrackPadding; } @override @@ -225,6 +234,7 @@ class ProgressIndicatorThemeData with Diagnosticable { 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)); } } diff --git a/packages/flutter/test/material/progress_indicator_test.dart b/packages/flutter/test/material/progress_indicator_test.dart index 103e9396e88..d38988e8013 100644 --- a/packages/flutter/test/material/progress_indicator_test.dart +++ b/packages/flutter/test/material/progress_indicator_test.dart @@ -1566,6 +1566,7 @@ 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( @@ -1576,13 +1577,23 @@ void main() { ), )); - expect(tester.getSize(find.byType(CircularProgressIndicator)), equals(const Size(48, 48))); + 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, 46.0, 46.0), + rect: const Rect.fromLTRB(2.0, 2.0, 38.0, 38.0), color: theme.colorScheme.secondaryContainer, strokeWidth: 4.0, strokeCap: StrokeCap.round, @@ -1590,7 +1601,7 @@ void main() { ) // Active indicator. ..arc( - rect: const Rect.fromLTRB(2.0, 2.0, 46.0, 46.0), + rect: const Rect.fromLTRB(2.0, 2.0, 38.0, 38.0), color: theme.colorScheme.primary, strokeWidth: 4.0, strokeCap: StrokeCap.round, @@ -1604,6 +1615,7 @@ void main() { }); 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)), @@ -1612,13 +1624,23 @@ void main() { // Advance the animation. await tester.pump(const Duration(milliseconds: 200)); - expect(tester.getSize(find.byType(CircularProgressIndicator)), equals(const Size(48, 48))); + 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, 46.0, 46.0), + rect: const Rect.fromLTRB(2.0, 2.0, 38.0, 38.0), color: theme.colorScheme.primary, strokeWidth: 4.0, strokeCap: StrokeCap.round, @@ -1709,6 +1731,33 @@ void main() { 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 8f85a64ab0e..5f1b153cce6 100644 --- a/packages/flutter/test/material/progress_indicator_theme_test.dart +++ b/packages/flutter/test/material/progress_indicator_theme_test.dart @@ -40,6 +40,7 @@ void main() { strokeCap: StrokeCap.butt, constraints: BoxConstraints.tightFor(width: 80.0, height: 80.0), trackGap: 16.0, + circularTrackPadding: EdgeInsets.all(12.0), ).debugFillProperties(builder); final List description = builder.properties @@ -60,7 +61,8 @@ void main() { 'strokeAlign: 1.0', 'strokeCap: StrokeCap.butt', 'constraints: BoxConstraints(w=80.0, h=80.0)', - 'trackGap: 16.0' + 'trackGap: 16.0', + 'circularTrackPadding: EdgeInsets.all(12.0)' ])); }); @@ -237,6 +239,7 @@ void main() { 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, @@ -245,6 +248,7 @@ void main() { strokeAlign: strokeAlign, strokeCap: strokeCap, constraints: constraints, + circularTrackPadding: padding, ), ); await tester.pumpWidget( @@ -262,7 +266,10 @@ void main() { expect( tester.getSize(find.byType(CircularProgressIndicator)), - equals(Size(constraints.maxWidth, constraints.maxHeight)), + equals(Size( + constraints.maxWidth + padding.horizontal, + constraints.maxHeight + padding.vertical, + )), ); expect( find.byType(CircularProgressIndicator), @@ -294,6 +301,7 @@ void main() { 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, @@ -303,6 +311,7 @@ void main() { strokeCap: strokeCap, constraints: constraints, trackGap: trackGap, + circularTrackPadding: padding, ), ); await tester.pumpWidget( @@ -319,9 +328,17 @@ void main() { ), ); + 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(constraints.maxWidth, constraints.maxHeight)), + equals(Size( + indicatorBoxSize.width + padding.horizontal, + indicatorBoxSize.height + padding.vertical, + )), ); expect( find.byType(CircularProgressIndicator), From b13770f65a4513fe977b935804b0a065fc6cccd7 Mon Sep 17 00:00:00 2001 From: Gray Mackall <34871572+gmackall@users.noreply.github.com> Date: Fri, 22 Nov 2024 11:00:19 -0800 Subject: [PATCH 179/386] Manually update strings after dca37ad, and turn `packages_autoroller` back on (#159343) Updates strings to reflect changes from https://github.com/flutter/flutter/commit/dca37ad17ff0354924f9b5bbbcbb2ce6ed819230 Reason: https://github.com/flutter/flutter/issues/159316#issuecomment-2494445095 Fixes https://github.com/flutter/flutter/issues/159316 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [ ] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --------- Co-authored-by: Gray Mackall --- .ci.yaml | 1 - dev/benchmarks/test_apps/stocks/lib/i18n/stock_strings_en.dart | 2 ++ dev/benchmarks/test_apps/stocks/lib/i18n/stock_strings_es.dart | 2 ++ 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.ci.yaml b/.ci.yaml index a9842eb91eb..1aa37d8e716 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -392,7 +392,6 @@ targets: - name: Linux packages_autoroller presubmit: false - bringup: true # https://github.com/flutter/flutter/issues/159316 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 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 From 7bf73e8bdc565760a4cdb3e6442935a57cc73772 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20Szcz=C4=99k?= Date: Fri, 22 Nov 2024 20:07:21 +0100 Subject: [PATCH 180/386] fix(ScrollAction): unsafe non-null assertion (#157855) This conditional most likely was meant to use `||` instead of `&&` operator to check if `notificationContext` is null OR if no Scrollable was found for this `notificationContext`. Using the AND operator instead causes the null assertion to fail when notificationContext is null, while also causing an assertion failure when notificationContext is not null, but no Scrollable is found for it. While at it, let's also deduplicate the Scrollable.maybeOf call. This fix is purely speculative, I didn't encounter this error, but rather was reading the ScrollAction's source and stumbled upon this. ~~With that said I wasn't actually able to trigger this error condition, thus why there are no tests included with this PR, if anyone has ideas on how this could be triggered, I'll be happy to include such test cases.~~ fixes #158063 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [ ] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- .../lib/src/widgets/scrollable_helpers.dart | 13 +-- .../test/widgets/scrollable_helpers_test.dart | 85 +++++++++++++++++++ 2 files changed, 92 insertions(+), 6 deletions(-) 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/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()); } From fc2254cca8bef21a9bc4ee43adfb96409967acbc Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Fri, 22 Nov 2024 14:25:07 -0500 Subject: [PATCH 181/386] Roll Flutter Engine from 6f941c961b05 to 202506d686e3 (10 revisions) (#159345) https://github.com/flutter/engine/compare/6f941c961b05...202506d686e3 2024-11-22 jonahwilliams@google.com [Impeller] cache and reuse openGL framebuffer attachments. (flutter/engine#56746) 2024-11-22 skia-flutter-autoroll@skia.org Roll Skia from 700e685861c8 to e7caf38140ce (25 revisions) (flutter/engine#56756) 2024-11-22 skia-flutter-autoroll@skia.org Roll Dart SDK from c1106f7e4cde to 141291fd570d (1 revision) (flutter/engine#56748) 2024-11-22 jonahwilliams@google.com [engine] more consistently flush dart event loop, run vsync callback immediately (flutter/engine#56738) 2024-11-22 chris@bracken.jp Extract backend-specific code in ShellTestPlatformView (flutter/engine#56722) 2024-11-22 chris@bracken.jp Eliminate ShellTestPlatformView::BackendType::kDefaultBackendType (flutter/engine#56744) 2024-11-22 skia-flutter-autoroll@skia.org Roll Skia from 2614590b4f32 to 700e685861c8 (1 revision) (flutter/engine#56725) 2024-11-22 skia-flutter-autoroll@skia.org Roll Dart SDK from b36e4d731d67 to c1106f7e4cde (12 revisions) (flutter/engine#56742) 2024-11-22 chinmaygarde@google.com [Impeller] libImpeller: A C++ wrapper to the Impeller API. (flutter/engine#56682) 2024-11-21 chinmaygarde@google.com [Impeller] Run simulator tests with Impeller enabled. (flutter/engine#56740) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 5fff410b1d8..a3031f4e051 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -6f941c961b05eebbe3cff2febb3bd91d6a02c87b +202506d686e317862d81548b8afcae9c9eecaa90 From b310baf41ad5a0c1ea1b681ca8ff2d07ac7d22c7 Mon Sep 17 00:00:00 2001 From: LongCatIsLooong <31859944+LongCatIsLooong@users.noreply.github.com> Date: Fri, 22 Nov 2024 11:39:37 -0800 Subject: [PATCH 182/386] Temporarily change tests to accommodate new `SemanticsAction` value (#159108) This is for fixing a test failure in an engine PR that introduces a new `SemanticsAction`: https://github.com/flutter/engine/pull/56606/files The test will be updated in the future to remove the index-based predicate. failure: https://logs.chromium.org/logs/flutter/buildbucket/cr-buildbucket/8730901009848520305/+/u/run_test.dart_for_web_tests_shard_and_subshard_1/stdout ## Pre-launch Checklist - [ ] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [ ] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [ ] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [ ] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [ ] I updated/added relevant documentation (doc comments with `///`). - [ ] I added new tests to check the change I am making, or this PR is [test-exempt]. - [ ] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [ ] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- packages/flutter/test/widgets/semantics_test.dart | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/flutter/test/widgets/semantics_test.dart b/packages/flutter/test/widgets/semantics_test.dart index 66dcd7ddb0f..171c04a1760 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 + ..removeWhere((SemanticsAction action) => action.index == 1 << 23); const int expectedId = 1; final TestSemantics expectedSemantics = TestSemantics.root( From d29a888bf2dfd87f065013145a4853901542b4a4 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Fri, 22 Nov 2024 11:41:08 -0800 Subject: [PATCH 183/386] Replace `\r\n` code with Dart SDK standard conventions. (#159346) Also deleted a file that appeared to be unused. --- .../bin/tasks/build_aar_module_test.dart | 14 ++++++-------- ...build_android_host_app_with_module_aar.dart | 13 ++++++------- ...ld_android_host_app_with_module_source.dart | 13 ++++++------- .../tasks/gradle_plugin_light_apk_test.dart | 2 +- .../module_custom_host_app_name_test.dart | 9 ++++----- .../bin/tasks/plugin_dependencies_test.dart | 18 ++++++++---------- dev/devicelab/lib/framework/apk_utils.dart | 8 +++----- .../new_gallery/test/utils.dart | 6 ------ 8 files changed, 34 insertions(+), 49 deletions(-) delete mode 100644 dev/integration_tests/new_gallery/test/utils.dart 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..3f5457b7d58 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) { @@ -79,8 +78,8 @@ 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 { @@ -111,16 +110,16 @@ 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 { 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..6eb381ce359 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) { @@ -79,8 +78,8 @@ 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 { @@ -111,16 +110,16 @@ 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 { 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..332e8ac4315 100644 --- a/dev/devicelab/bin/tasks/gradle_plugin_light_apk_test.dart +++ b/dev/devicelab/bin/tasks/gradle_plugin_light_apk_test.dart @@ -211,7 +211,7 @@ Future main() async { section('Configure'); project.addPlugin('plugin_under_test', - value: '$platformLineSep path: ${pluginDir.path}'); + value: '${Platform.lineTerminator} path: ${pluginDir.path}'); await project.addCustomBuildType('local', initWith: 'debug'); await project.getPackages(); 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..d5aa93f5120 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 { diff --git a/dev/devicelab/bin/tasks/plugin_dependencies_test.dart b/dev/devicelab/bin/tasks/plugin_dependencies_test.dart index e0f6178c9f0..54f9979dbc3 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. /// @@ -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); diff --git a/dev/devicelab/lib/framework/apk_utils.dart b/dev/devicelab/lib/framework/apk_utils.dart index e9ebfea319c..d0ce8ee289c 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', @@ -280,8 +278,8 @@ android { 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', + '${Platform.lineTerminator}dependencies:${Platform.lineTerminator}', + '${Platform.lineTerminator}dependencies:${Platform.lineTerminator} $plugin: $value${Platform.lineTerminator}', ); pubspec.writeAsStringSync(content, flush: true); } @@ -336,7 +334,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: diff --git a/dev/integration_tests/new_gallery/test/utils.dart b/dev/integration_tests/new_gallery/test/utils.dart deleted file mode 100644 index 9218e2ee8d7..00000000000 --- a/dev/integration_tests/new_gallery/test/utils.dart +++ /dev/null @@ -1,6 +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. - -// Replace Windows line endings with Unix line endings -String standardizeLineEndings(String str) => str.replaceAll('\r\n', '\n'); From 9cffcefa15ceac3d72b1a5150fb180c1592cebcc Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Fri, 22 Nov 2024 15:18:25 -0500 Subject: [PATCH 184/386] Roll Flutter Engine from 202506d686e3 to 9384df4425fd (2 revisions) (#159348) https://github.com/flutter/engine/compare/202506d686e3...9384df4425fd 2024-11-22 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from zhFzwYCH-N_wasTnM... to D5CBHuB2c-v3Zai-c... (flutter/engine#56757) 2024-11-22 skia-flutter-autoroll@skia.org Roll Dart SDK from 141291fd570d to 8b65a7a628e2 (1 revision) (flutter/engine#56755) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from zhFzwYCH-N_w to D5CBHuB2c-v3 If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index a3031f4e051..57fc2d0d922 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -202506d686e317862d81548b8afcae9c9eecaa90 +9384df4425fd25bac1bd92a4a4ea65b2e7fa8d10 diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index 88f94ccb72f..c1583669965 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -zhFzwYCH-N_wasTnMUjFf2dzRXRIMjNPuX6LDgic7oAC +D5CBHuB2c-v3Zai-ctZfl5OU4d13Q1Af5LYFMrzdpVIC From fe087fff95f513412223c9a184e66374c0c02b9b Mon Sep 17 00:00:00 2001 From: chunhtai <47866232+chunhtai@users.noreply.github.com> Date: Fri, 22 Nov 2024 14:47:59 -0800 Subject: [PATCH 185/386] Set stable color for semantics debugger (#157884) fixes https://github.com/flutter/flutter/issues/156242 ## Pre-launch Checklist - [ ] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [ ] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [ ] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [ ] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [ ] I updated/added relevant documentation (doc comments with `///`). - [ ] I added new tests to check the change I am making, or this PR is [test-exempt]. - [ ] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [ ] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- .../flutter/lib/src/semantics/semantics.dart | 3 +-- .../lib/src/widgets/semantics_debugger.dart | 26 ++++++++++++++++--- .../test/widgets/semantics_debugger_test.dart | 20 ++++++++++++++ 3 files changed, 43 insertions(+), 6 deletions(-) diff --git a/packages/flutter/lib/src/semantics/semantics.dart b/packages/flutter/lib/src/semantics/semantics.dart index 1934aa2b80c..2df357ee82b 100644 --- a/packages/flutter/lib/src/semantics/semantics.dart +++ b/packages/flutter/lib/src/semantics/semantics.dart @@ -2092,8 +2092,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!) { 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/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(); From 07690a69b0067f8a8471470f7314a3294591033d Mon Sep 17 00:00:00 2001 From: "auto-submit[bot]" <98614782+auto-submit[bot]@users.noreply.github.com> Date: Fri, 22 Nov 2024 15:20:59 -0800 Subject: [PATCH 186/386] Reverts "Set stable color for semantics debugger (#157884)" (#159354) Reverts: flutter/flutter#157884 Initiated by: chunhtai Reason for reverting: merge by mistake Original PR Author: chunhtai Reviewed By: {LongCatIsLooong} This change reverts the following previous change: fixes https://github.com/flutter/flutter/issues/156242 ## Pre-launch Checklist - [ ] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [ ] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [ ] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [ ] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [ ] I updated/added relevant documentation (doc comments with `///`). - [ ] I added new tests to check the change I am making, or this PR is [test-exempt]. - [ ] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [ ] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md Co-authored-by: auto-submit[bot] --- .../flutter/lib/src/semantics/semantics.dart | 3 ++- .../lib/src/widgets/semantics_debugger.dart | 26 +++---------------- .../test/widgets/semantics_debugger_test.dart | 20 -------------- 3 files changed, 6 insertions(+), 43 deletions(-) diff --git a/packages/flutter/lib/src/semantics/semantics.dart b/packages/flutter/lib/src/semantics/semantics.dart index 2df357ee82b..1934aa2b80c 100644 --- a/packages/flutter/lib/src/semantics/semantics.dart +++ b/packages/flutter/lib/src/semantics/semantics.dart @@ -2092,7 +2092,8 @@ class SemanticsNode with DiagnosticableTreeMixin { /// Visits the immediate children of this node. /// /// This function calls visitor for each immediate child until visitor returns - /// false. + /// false. Returns true if all the visitor calls returned true, otherwise + /// returns false. void visitChildren(SemanticsNodeVisitor visitor) { if (_children != null) { for (final SemanticsNode child in _children!) { diff --git a/packages/flutter/lib/src/widgets/semantics_debugger.dart b/packages/flutter/lib/src/widgets/semantics_debugger.dart index 97d73e39675..937e89d0014 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), 0, 0); + _paint(canvas, rootNode, _findDepth(rootNode)); } 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, int indexInParent, int level) { + void _paint(Canvas canvas, SemanticsNode node, int rank) { canvas.save(); if (node.transform != null) { canvas.transform(node.transform!.storage); } final Rect rect = node.rect; if (!rect.isEmpty) { - final Color lineColor = _colorForNode(indexInParent, level); + final Color lineColor = Color(0xFF000000 + math.Random(node.id).nextInt(0xFFFFFF)); final Rect innerRect = rect.deflate(rank * 1.0); if (innerRect.isEmpty) { final Paint fill = Paint() @@ -361,31 +361,13 @@ 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, childIndex, childLevel); - childIndex += 1; + _paint(canvas, child, childRank); 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/test/widgets/semantics_debugger_test.dart b/packages/flutter/test/widgets/semantics_debugger_test.dart index 7edcffd50d9..47b8243300e 100644 --- a/packages/flutter/test/widgets/semantics_debugger_test.dart +++ b/packages/flutter/test/widgets/semantics_debugger_test.dart @@ -61,26 +61,6 @@ 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(); From 0d8c57a0a1984f8c4efb2e4eabfe2fb62ad53c80 Mon Sep 17 00:00:00 2001 From: "auto-submit[bot]" <98614782+auto-submit[bot]@users.noreply.github.com> Date: Fri, 22 Nov 2024 15:55:02 -0800 Subject: [PATCH 187/386] Reverts "Roll Flutter Engine from 202506d686e3 to 9384df4425fd (2 revisions) (#159348)" (#159359) Reverts: flutter/flutter#159348 Initiated by: hannah-hyj Reason for reverting: tree is red on " Linux_build_test flutter_gallery__transition_perf_hybrid" after this PR Original PR Author: engine-flutter-autoroll Reviewed By: {fluttergithubbot} This change reverts the following previous change: https://github.com/flutter/engine/compare/202506d686e3...9384df4425fd 2024-11-22 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from zhFzwYCH-N_wasTnM... to D5CBHuB2c-v3Zai-c... (flutter/engine#56757) 2024-11-22 skia-flutter-autoroll@skia.org Roll Dart SDK from 141291fd570d to 8b65a7a628e2 (1 revision) (flutter/engine#56755) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from zhFzwYCH-N_w to D5CBHuB2c-v3 If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md Co-authored-by: auto-submit[bot] --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 57fc2d0d922..a3031f4e051 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -9384df4425fd25bac1bd92a4a4ea65b2e7fa8d10 +202506d686e317862d81548b8afcae9c9eecaa90 diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index c1583669965..88f94ccb72f 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -D5CBHuB2c-v3Zai-ctZfl5OU4d13Q1Af5LYFMrzdpVIC +zhFzwYCH-N_wasTnMUjFf2dzRXRIMjNPuX6LDgic7oAC From 5e2a62a602222bf922aee6e6904398a146d77c3c Mon Sep 17 00:00:00 2001 From: "auto-submit[bot]" <98614782+auto-submit[bot]@users.noreply.github.com> Date: Fri, 22 Nov 2024 23:59:18 +0000 Subject: [PATCH 188/386] Reverts "Roll Flutter Engine from 6f941c961b05 to 202506d686e3 (10 revisions) (#159345)" (#159360) Reverts: flutter/flutter#159345 Initiated by: hannah-hyj Reason for reverting: tree is red on " Linux_build_test flutter_gallery__transition_perf_hybrid" after engine auto roll Original PR Author: engine-flutter-autoroll Reviewed By: {fluttergithubbot} This change reverts the following previous change: https://github.com/flutter/engine/compare/6f941c961b05...202506d686e3 2024-11-22 jonahwilliams@google.com [Impeller] cache and reuse openGL framebuffer attachments. (flutter/engine#56746) 2024-11-22 skia-flutter-autoroll@skia.org Roll Skia from 700e685861c8 to e7caf38140ce (25 revisions) (flutter/engine#56756) 2024-11-22 skia-flutter-autoroll@skia.org Roll Dart SDK from c1106f7e4cde to 141291fd570d (1 revision) (flutter/engine#56748) 2024-11-22 jonahwilliams@google.com [engine] more consistently flush dart event loop, run vsync callback immediately (flutter/engine#56738) 2024-11-22 chris@bracken.jp Extract backend-specific code in ShellTestPlatformView (flutter/engine#56722) 2024-11-22 chris@bracken.jp Eliminate ShellTestPlatformView::BackendType::kDefaultBackendType (flutter/engine#56744) 2024-11-22 skia-flutter-autoroll@skia.org Roll Skia from 2614590b4f32 to 700e685861c8 (1 revision) (flutter/engine#56725) 2024-11-22 skia-flutter-autoroll@skia.org Roll Dart SDK from b36e4d731d67 to c1106f7e4cde (12 revisions) (flutter/engine#56742) 2024-11-22 chinmaygarde@google.com [Impeller] libImpeller: A C++ wrapper to the Impeller API. (flutter/engine#56682) 2024-11-21 chinmaygarde@google.com [Impeller] Run simulator tests with Impeller enabled. (flutter/engine#56740) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md Co-authored-by: auto-submit[bot] --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index a3031f4e051..5fff410b1d8 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -202506d686e317862d81548b8afcae9c9eecaa90 +6f941c961b05eebbe3cff2febb3bd91d6a02c87b From 5efd759085839180c3d623ff3020b4d85c5449ec Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Fri, 22 Nov 2024 16:25:46 -0800 Subject: [PATCH 189/386] Remove now unused `apk-health-tests`. Can always re-add in the future. (#159349) https://github.com/flutter/flutter/issues/159000 resolved (for now). --- .ci.yaml | 23 ------------------- TESTOWNERS | 1 - dev/bots/test.dart | 14 ----------- .../android_e2e_api_test.dart | 4 ---- ...d_gradle_deprecated_plugin_apply_test.dart | 4 ---- ...tter_plugins_strings_in_comments_test.dart | 4 ---- ...roid_gradle_print_build_variants_test.dart | 4 ---- ...android_plugin_example_app_build_test.dart | 4 ---- ...ter_build_with_compilation_error_test.dart | 4 ---- .../native_assets_agp_version_test.dart | 5 ---- .../isolated/native_assets_test.dart | 2 -- ...e_assets_without_cbuild_assemble_test.dart | 4 ---- 12 files changed, 73 deletions(-) diff --git a/.ci.yaml b/.ci.yaml index 1aa37d8e716..0a61bd3ed8b 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -1297,29 +1297,6 @@ targets: - bin/** - .ci.yaml - - name: Linux flutter_build_apk_health_tests - recipe: flutter/flutter_drone - # WARNING: Do *NOT* enable. This intended for testing on CI only. - # Ask matanlurey@ or @gmackall if you have any questions. - bringup: true - timeout: 60 - properties: - add_recipes_cq: "true" - dependencies: >- - [ - {"dependency": "android_sdk", "version": "version:35v1"}, - {"dependency": "chrome_and_driver", "version": "version:125.0.6422.141"}, - {"dependency": "clang", "version": "git_revision:5d5aba78dbbee75508f01bcaa69aedb2ab79065a"}, - {"dependency": "cmake", "version": "build_id:8787856497187628321"}, - {"dependency": "goldctl", "version": "git_revision:2387d6fff449587eecbb7e45b2692ca0710b63b9"}, - {"dependency": "ninja", "version": "version:1.9.0"}, - {"dependency": "open_jdk", "version": "version:17"} - ] - shard: flutter_build_apk_health_tests - tags: > - ["framework", "hostonly", "shard", "linux"] - test_timeout_secs: "2700" - - name: Linux android_preview_tool_integration_tests recipe: flutter/flutter_drone timeout: 60 diff --git a/TESTOWNERS b/TESTOWNERS index 5715846e80c..76c8b2bef2b 100644 --- a/TESTOWNERS +++ b/TESTOWNERS @@ -327,7 +327,6 @@ # coverage @goderbauer @flutter/infra # customer_testing @Piinks @flutter/framework # docs @Piinks @flutter/framework -# flutter_build_apk_health_tests @matanlurey @gmackall # flutter_driver_android_test @matanlurey @johnmccutchan # flutter_packaging @christopherfujino @flutter/infra # flutter_plugins @stuartmorgan @flutter/plugin diff --git a/dev/bots/test.dart b/dev/bots/test.dart index 4077a937e15..f88ce8ca896 100644 --- a/dev/bots/test.dart +++ b/dev/bots/test.dart @@ -136,7 +136,6 @@ Future main(List args) async { 'tool_tests': _runToolTests, 'web_tool_tests': _runWebToolTests, 'tool_integration_tests': _runIntegrationToolTests, - 'flutter_build_apk_health_tests': _runFlutterBuildApkHealthTests, 'android_preview_tool_integration_tests': androidPreviewIntegrationToolTestsRunner, 'android_java11_tool_integration_tests': androidJava11IntegrationToolTestsRunner, 'tool_host_cross_arch_tests': _runToolHostCrossArchTests, @@ -239,19 +238,6 @@ Future _runIntegrationToolTests() async { ); } -Future _runFlutterBuildApkHealthTests() async { - await runDartTest( - _toolsPath, - forceSingleCore: true, - testPaths: [ - path.join(_toolsPath, 'test', 'integration.shard'), - ], - collectMetrics: true, - runSkipped: true, - tags: ['flutter-build-apk'], - ); -} - Future _runToolTests() async { await selectSubshard({ 'general': _runGeneralToolTests, diff --git a/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart b/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart index 599f66a6060..277be58754b 100644 --- a/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart @@ -2,10 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// TODO(matanlurey): Remove after debugging https://github.com/flutter/flutter/issues/159000. -@Tags(['flutter-build-apk']) -library; - import 'package:file/file.dart'; import 'package:flutter_tools/src/base/io.dart'; diff --git a/packages/flutter_tools/test/integration.shard/android_gradle_deprecated_plugin_apply_test.dart b/packages/flutter_tools/test/integration.shard/android_gradle_deprecated_plugin_apply_test.dart index 20221f174b6..7679c46ea6b 100644 --- a/packages/flutter_tools/test/integration.shard/android_gradle_deprecated_plugin_apply_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_gradle_deprecated_plugin_apply_test.dart @@ -2,10 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// TODO(matanlurey): Remove after debugging https://github.com/flutter/flutter/issues/159000. -@Tags(['flutter-build-apk']) -library; - import 'dart:convert'; import 'package:file/file.dart'; diff --git a/packages/flutter_tools/test/integration.shard/android_gradle_legacy_flutter_plugins_strings_in_comments_test.dart b/packages/flutter_tools/test/integration.shard/android_gradle_legacy_flutter_plugins_strings_in_comments_test.dart index 4daf82441ae..b95b226c256 100644 --- a/packages/flutter_tools/test/integration.shard/android_gradle_legacy_flutter_plugins_strings_in_comments_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_gradle_legacy_flutter_plugins_strings_in_comments_test.dart @@ -2,10 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// TODO(matanlurey): Remove after debugging https://github.com/flutter/flutter/issues/159000. -@Tags(['flutter-build-apk']) -library; - // This test can be removed once https://github.com/flutter/flutter/issues/155484 is resolved. import 'package:flutter_tools/src/base/file_system.dart'; diff --git a/packages/flutter_tools/test/integration.shard/android_gradle_print_build_variants_test.dart b/packages/flutter_tools/test/integration.shard/android_gradle_print_build_variants_test.dart index e8f60aff814..5997054132d 100644 --- a/packages/flutter_tools/test/integration.shard/android_gradle_print_build_variants_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_gradle_print_build_variants_test.dart @@ -2,10 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// TODO(matanlurey): Remove after debugging https://github.com/flutter/flutter/issues/159000. -@Tags(['flutter-build-apk']) -library; - import 'dart:convert'; import 'package:collection/collection.dart'; diff --git a/packages/flutter_tools/test/integration.shard/android_plugin_example_app_build_test.dart b/packages/flutter_tools/test/integration.shard/android_plugin_example_app_build_test.dart index 67a70cf04ea..57d84ddcf4d 100644 --- a/packages/flutter_tools/test/integration.shard/android_plugin_example_app_build_test.dart +++ b/packages/flutter_tools/test/integration.shard/android_plugin_example_app_build_test.dart @@ -2,10 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// TODO(matanlurey): Remove after debugging https://github.com/flutter/flutter/issues/159000. -@Tags(['flutter-build-apk']) -library; - import 'package:file_testing/file_testing.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/io.dart'; diff --git a/packages/flutter_tools/test/integration.shard/flutter_build_with_compilation_error_test.dart b/packages/flutter_tools/test/integration.shard/flutter_build_with_compilation_error_test.dart index 7c5d2aefa64..77ff8df921f 100644 --- a/packages/flutter_tools/test/integration.shard/flutter_build_with_compilation_error_test.dart +++ b/packages/flutter_tools/test/integration.shard/flutter_build_with_compilation_error_test.dart @@ -2,10 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// TODO(matanlurey): Remove after debugging https://github.com/flutter/flutter/issues/159000. -@Tags(['flutter-build-apk']) -library; - import 'package:file/file.dart'; import 'package:flutter_tools/src/base/io.dart'; diff --git a/packages/flutter_tools/test/integration.shard/isolated/native_assets_agp_version_test.dart b/packages/flutter_tools/test/integration.shard/isolated/native_assets_agp_version_test.dart index 6973af8c648..4272a7552ff 100644 --- a/packages/flutter_tools/test/integration.shard/isolated/native_assets_agp_version_test.dart +++ b/packages/flutter_tools/test/integration.shard/isolated/native_assets_agp_version_test.dart @@ -2,11 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// TODO(matanlurey): Remove after debugging https://github.com/flutter/flutter/issues/159000. -@Tags(['flutter-build-apk']) -@Timeout(Duration(minutes: 10)) -library; - import 'dart:io'; import 'package:file/file.dart'; diff --git a/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart b/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart index e86fea21cea..09edb563729 100644 --- a/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart +++ b/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart @@ -10,8 +10,6 @@ // contain the native assets mapping. // When doing a hot reload, this mapping must stay in place. -// TODO(matanlurey): Remove after debugging https://github.com/flutter/flutter/issues/159000. -@Tags(['flutter-build-apk']) @Timeout(Duration(minutes: 10)) library; diff --git a/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart b/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart index 81b1c050bae..6f4eb127008 100644 --- a/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart +++ b/packages/flutter_tools/test/integration.shard/isolated/native_assets_without_cbuild_assemble_test.dart @@ -2,10 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// TODO(matanlurey): Remove after debugging https://github.com/flutter/flutter/issues/159000. -@Tags(['flutter-build-apk']) -library; - import 'dart:io' as io; import 'package:file/file.dart'; From 4b46b8066173cf4f7843b9aab86ce28c046274ec Mon Sep 17 00:00:00 2001 From: Mikhail Novoseltsev <51940183+Sameri11@users.noreply.github.com> Date: Sat, 23 Nov 2024 07:27:18 +0700 Subject: [PATCH 190/386] doctor: make JDK validation message more descriptive (#157280) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This PR attempts to improve clarity of androids section of `flutter doctor -v` output by providing explicit information about which JDK is being used and how to configure a different one if needed. ### Before ```console • Java binary at: /Users/user/Applications/Android Studio Ladybug Feature Drop 2024.2.2 Canary 2.app/Contents/jbr/Contents/Home/bin/java ``` ### After 1. When JDK is from Android Studio: ```console • Java binary at: /Users/users/Applications/Android Studio Ladybug Feature Drop 2024.2.2 Canary 2.app/Contents/jbr/Contents/Home/bin/java This is the JDK bundled with latest Android Studio installation To manually set a custom JDK path, use: `flutter config --jdk-dir="path/to/jdk"` ``` 2. When JDK is from JAVA_HOME env variable: ```console • Java binary at: /Users/user/Applications/Android Studio Ladybug Feature Drop 2024.2.2 Canary 2.app/Contents/jbr/Contents/Home/bin/java This JDK is specified by JAVA_HOME environment variable To manually set a custom JDK path, use: `flutter config --jdk-dir="path/to/jdk"` ``` 3. When path to JDK is set in flutter config: ```console • Java binary at: /Users/user/Applications/Android Studio Ladybug Feature Drop 2024.2.2 Canary 2.app/Contents/jbr/Contents/Home/bin/java This JDK was found in system PATH To change current JDK, run: `flutter config --jdk-dir="path/to/jdk"` ``` 4. When java binary is found in PATH (as fallback) ```console • Java binary at: /Users/user/Applications/Android Studio Ladybug Feature Drop 2024.2.2 Canary 2.app/Contents/jbr/Contents/Home/bin/java This JDK is specified in Flutter configuration To manually set a custom JDK path, use: `flutter config --jdk-dir="path/to/jdk"` ``` ### Motivation I think it's described in https://github.com/flutter/flutter/issues/153156#issuecomment-2336814991. TLDR; many developers struggle with Java-related issues and more verbose doctor's output will (presumably) improve DX in that part. fixes #153156 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --------- Co-authored-by: Andrew Kolos --- .../lib/src/android/android_workflow.dart | 30 +++- .../flutter_tools/lib/src/android/java.dart | 39 ++++- .../lib/src/base/user_messages.dart | 1 - .../android/android_workflow_test.dart | 140 ++++++++++++++++++ .../test/general.shard/android/java_test.dart | 13 ++ packages/flutter_tools/test/src/fakes.dart | 4 + 6 files changed, 218 insertions(+), 9 deletions(-) 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/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/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/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/src/fakes.dart b/packages/flutter_tools/test/src/fakes.dart index ec5d5296b15..42ccf2b57bd 100644 --- a/packages/flutter_tools/test/src/fakes.dart +++ b/packages/flutter_tools/test/src/fakes.dart @@ -670,6 +670,7 @@ class FakeAndroidStudio extends Fake implements AndroidStudio { class FakeJava extends Fake implements Java { FakeJava({ this.javaHome = '/android-studio/jbr', + this.javaSource = JavaSource.androidStudio, String binary = '/android-studio/jbr/bin/java', Version? version, bool canRun = true, @@ -687,6 +688,9 @@ class FakeJava extends Fake implements Java { @override String binaryPath; + @override + JavaSource javaSource; + final Map _environment; final bool _canRun; From 0e896221b4903b674dbdb9d4d2da65fa83c6d84e Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Fri, 22 Nov 2024 21:07:25 -0500 Subject: [PATCH 191/386] Roll Flutter Engine from 6f941c961b05 to f776c3a7647c (20 revisions) (#159364) https://github.com/flutter/engine/compare/6f941c961b05...f776c3a7647c 2024-11-22 skia-flutter-autoroll@skia.org Roll Skia from e7caf38140ce to c3d9596a93f8 (2 revisions) (flutter/engine#56765) 2024-11-22 98614782+auto-submit[bot]@users.noreply.github.com Reverts "[engine] more consistently flush dart event loop, run vsync callback immediately (#56738)" (flutter/engine#56767) 2024-11-22 skia-flutter-autoroll@skia.org Roll Dart SDK from 8b65a7a628e2 to eb01a0430f72 (2 revisions) (flutter/engine#56764) 2024-11-22 jonahwilliams@google.com [Impeller] delete Impeller sim opt out. (flutter/engine#56706) 2024-11-22 jason-simmons@users.noreply.github.com [Impeller] Ensure that SnapshotControllerImpeller has a rendering context before creating the snapshot (flutter/engine#56743) 2024-11-22 flar@google.com [DisplayList] migrate DlColorSource objects to Impeller geometry (flutter/engine#56735) 2024-11-22 chinmaygarde@google.com [Impeller] libImpeller: Tinker on the README. (flutter/engine#56761) 2024-11-22 jonahwilliams@google.com [Impeller] dont create temp vec for discard. (flutter/engine#56759) 2024-11-22 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from zhFzwYCH-N_wasTnM... to D5CBHuB2c-v3Zai-c... (flutter/engine#56757) 2024-11-22 skia-flutter-autoroll@skia.org Roll Dart SDK from 141291fd570d to 8b65a7a628e2 (1 revision) (flutter/engine#56755) 2024-11-22 jonahwilliams@google.com [Impeller] cache and reuse openGL framebuffer attachments. (flutter/engine#56746) 2024-11-22 skia-flutter-autoroll@skia.org Roll Skia from 700e685861c8 to e7caf38140ce (25 revisions) (flutter/engine#56756) 2024-11-22 skia-flutter-autoroll@skia.org Roll Dart SDK from c1106f7e4cde to 141291fd570d (1 revision) (flutter/engine#56748) 2024-11-22 jonahwilliams@google.com [engine] more consistently flush dart event loop, run vsync callback immediately (flutter/engine#56738) 2024-11-22 chris@bracken.jp Extract backend-specific code in ShellTestPlatformView (flutter/engine#56722) 2024-11-22 chris@bracken.jp Eliminate ShellTestPlatformView::BackendType::kDefaultBackendType (flutter/engine#56744) 2024-11-22 skia-flutter-autoroll@skia.org Roll Skia from 2614590b4f32 to 700e685861c8 (1 revision) (flutter/engine#56725) 2024-11-22 skia-flutter-autoroll@skia.org Roll Dart SDK from b36e4d731d67 to c1106f7e4cde (12 revisions) (flutter/engine#56742) 2024-11-22 chinmaygarde@google.com [Impeller] libImpeller: A C++ wrapper to the Impeller API. (flutter/engine#56682) 2024-11-21 chinmaygarde@google.com [Impeller] Run simulator tests with Impeller enabled. (flutter/engine#56740) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from zhFzwYCH-N_w to D5CBHuB2c-v3 If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 5fff410b1d8..f32836610fe 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -6f941c961b05eebbe3cff2febb3bd91d6a02c87b +f776c3a7647c8854fced07a6e2d1924f608f4d27 diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index 88f94ccb72f..c1583669965 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -zhFzwYCH-N_wasTnMUjFf2dzRXRIMjNPuX6LDgic7oAC +D5CBHuB2c-v3Zai-ctZfl5OU4d13Q1Af5LYFMrzdpVIC From 561b7cb474fd54bbba7c6afbe2b0b88cb0ca1a88 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sat, 23 Nov 2024 01:06:32 -0500 Subject: [PATCH 192/386] Roll Flutter Engine from f776c3a7647c to 19563e5c72a9 (3 revisions) (#159369) https://github.com/flutter/engine/compare/f776c3a7647c...19563e5c72a9 2024-11-23 skia-flutter-autoroll@skia.org Roll Dart SDK from eb01a0430f72 to 202083b79ac5 (1 revision) (flutter/engine#56772) 2024-11-23 skia-flutter-autoroll@skia.org Roll Skia from c3d9596a93f8 to 6a3f77189dde (1 revision) (flutter/engine#56771) 2024-11-23 chris@bracken.jp iOS: Fix typo in fluttterViewController (flutter/engine#56770) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index f32836610fe..b5f201faa51 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -f776c3a7647c8854fced07a6e2d1924f608f4d27 +19563e5c72a9e26ccad48b3213193c4762831077 From d39c3532578a05d208e16d080a234a5f2c40e4ba Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sat, 23 Nov 2024 05:10:30 -0500 Subject: [PATCH 193/386] Roll Flutter Engine from 19563e5c72a9 to b382d17a27d1 (1 revision) (#159371) https://github.com/flutter/engine/compare/19563e5c72a9...b382d17a27d1 2024-11-23 skia-flutter-autoroll@skia.org Roll Dart SDK from 202083b79ac5 to df716eaa6ed2 (1 revision) (flutter/engine#56773) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index b5f201faa51..f7c03f2822f 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -19563e5c72a9e26ccad48b3213193c4762831077 +b382d17a27d13e38313f527ca0693d35ad670e8a From 773b42f4fb80583db8f7424f3f787dd802ddfc21 Mon Sep 17 00:00:00 2001 From: Bruno Leroux Date: Sat, 23 Nov 2024 12:43:22 +0100 Subject: [PATCH 194/386] Do not rely on Leader/Follower to position DropdownMenu menu (#158930) ## Description This PR removes `DropdownMenu` usage of Leader/Follower. Leader/Follower positioning was introduced in https://github.com/flutter/flutter/pull/154667 which uses Leader/Follower approach to fix some weird positioning issues (such as https://github.com/flutter/flutter/issues/149037). Unfortunately, it also introduces some regressions, see: - https://github.com/flutter/flutter/issues/157916 - https://github.com/flutter/flutter/issues/158924 Because https://github.com/flutter/flutter/pull/154667 is already included in the beta channel, cherry-picking this PR should be considered. ## Context This PR is not a full revert and keeps Leader/Follower usage in `MenuAnchor` because this usage is optional and doesn't cause any regression. There are some ongoing work which might fix or mitigate this problem: - https://github.com/flutter/flutter/pull/157921 - https://github.com/flutter/flutter/pull/158255 ## Related Issue Fixes https://github.com/flutter/flutter/issues/157916 Fixes https://github.com/flutter/flutter/issues/158924 Reopens https://github.com/flutter/flutter/issues/123395 Reopens https://github.com/flutter/flutter/issues/149037 Reopens https://github.com/flutter/flutter/issues/151856 --- .../lib/src/material/dropdown_menu.dart | 1 - .../test/material/dropdown_menu_test.dart | 41 ------------------- 2 files changed, 42 deletions(-) diff --git a/packages/flutter/lib/src/material/dropdown_menu.dart b/packages/flutter/lib/src/material/dropdown_menu.dart index 7ae84b4fa03..def4ea08a24 100644 --- a/packages/flutter/lib/src/material/dropdown_menu.dart +++ b/packages/flutter/lib/src/material/dropdown_menu.dart @@ -902,7 +902,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( diff --git a/packages/flutter/test/material/dropdown_menu_test.dart b/packages/flutter/test/material/dropdown_menu_test.dart index 1156fe00a86..d78f5f14884 100644 --- a/packages/flutter/test/material/dropdown_menu_test.dart +++ b/packages/flutter/test/material/dropdown_menu_test.dart @@ -3366,47 +3366,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( From da188452a6490a4fcda02698f02ed48a47617468 Mon Sep 17 00:00:00 2001 From: Albert Wolszon Date: Sat, 23 Nov 2024 19:55:24 +0100 Subject: [PATCH 195/386] Allow add_format() in flutter gen-l10n DateTime format (#156297) This Pull Request extends the functionality of the `flutter gen-l10n` command (and its behavior during hot restart/reload) related to `DateFormat` type placeholders and their `format`. Until now, it was impossible to take advantage of `intl`'s `DateFormat.something().add_somethingElse()`. The `.add_x()` part was impossible to achieve. This PR adds the ability to take advantage of these methods over `DateFormat`, by adding the `add_` formats after the `+` character in the `format` in placeholder configuration. You can even have multiple added format parts if needed. All within a single placeholder.
Before the PR After the PR
```json { "bookingsPage_camo_dataLoaded": "CAMO data from {date} {time}.", "@bookingsPage_camo_dataLoaded": { "placeholders": { "date": { "type": "DateTime", "format": "yMMMd" }, "time": { "type": "DateTime", "format": "jm" } } }, } ``` ```json { "bookingsPage_camo_dataLoaded": "CAMO data from {date}.", "@bookingsPage_camo_dataLoaded": { "placeholders": { "date": { "type": "DateTime", "format": "yMMMd+jm" } } }, } ```
Resolves #155817. ## Next steps After this PR is merged, an update to [i18n | Flutter > Messages with dates](https://docs.flutter.dev/ui/accessibility-and-internationalization/internationalization#messages-with-dates) ([source](https://github.com/flutter/website/blob/main/src/content/ui/accessibility-and-internationalization/internationalization.md)) shall be made to include a mention of this new addition. ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --------- Co-authored-by: Andrew Kolos --- AUTHORS | 1 + .../lib/src/localizations/gen_l10n.dart | 22 ++++- .../src/localizations/gen_l10n_templates.dart | 4 +- .../lib/src/localizations/gen_l10n_types.dart | 12 ++- .../generate_localizations_test.dart | 98 +++++++++++++++++++ .../test/integration.shard/gen_l10n_test.dart | 79 +++++++-------- .../test_data/gen_l10n_project.dart | 18 +++- 7 files changed, 188 insertions(+), 46 deletions(-) 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/packages/flutter_tools/lib/src/localizations/gen_l10n.dart b/packages/flutter_tools/lib/src/localizations/gen_l10n.dart index 0ef68cff42a..c298bf9fed9 100644 --- a/packages/flutter_tools/lib/src/localizations/gen_l10n.dart +++ b/packages/flutter_tools/lib/src/localizations/gen_l10n.dart @@ -169,6 +169,16 @@ String generateDateFormattingLogic(Message message, LocaleInfo locale) { 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 ' @@ -178,9 +188,19 @@ String generateDateFormattingLogic(Message message, LocaleInfo locale) { ); } 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) 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 3f15740c46b..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)); 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 2bae97f0f83..e62b8904098 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, diff --git a/packages/flutter_tools/test/general.shard/generate_localizations_test.dart b/packages/flutter_tools/test/general.shard/generate_localizations_test.dart index 55a33a294be..5d36205b53d 100644 --- a/packages/flutter_tools/test/general.shard/generate_localizations_test.dart +++ b/packages/flutter_tools/test/general.shard/generate_localizations_test.dart @@ -1686,6 +1686,104 @@ import 'output-localization-file_en.dart' deferred as output-localization-file_e expect(content, contains(r"DateFormat('asdf o\'clock', localeName)")); }); + testWithoutContext('handles adding two valid formats', () { + setupLocalizations({ + 'en': ''' +{ + "loggedIn": "Last logged in on {lastLoginDate}", + "@loggedIn": { + "placeholders": { + "lastLoginDate": { + "type": "DateTime", + "format": "yMd+jms" + } + } + } +}''' + }); + final String content = getGeneratedFileContent(locale: 'en'); + expect(content, contains(r'DateFormat.yMd(localeName).add_jms()')); + }); + + testWithoutContext('handles adding three valid formats', () { + setupLocalizations({ + 'en': ''' +{ + "loggedIn": "Last logged in on {lastLoginDate}", + "@loggedIn": { + "placeholders": { + "lastLoginDate": { + "type": "DateTime", + "format": "yMMMMEEEEd+QQQQ+Hm" + } + } + } +}''' + }); + final String content = getGeneratedFileContent(locale: 'en'); + expect(content, contains(r'DateFormat.yMMMMEEEEd(localeName).add_QQQQ().add_Hm()')); + }); + + testWithoutContext('throws an exception when adding invalid formats', (){ + expect( + () { + setupLocalizations({ + 'en': ''' +{ + "loggedIn": "Last logged in on {lastLoginDate}", + "@loggedIn": { + "placeholders": { + "lastLoginDate": { + "type": "DateTime", + "format": "foo+bar+baz" + } + } + } +}''' + }); + }, + throwsA(isA().having( + (L10nException e) => e.message, + 'message', + allOf( + contains('"foo+bar+baz"'), + contains('lastLoginDate'), + contains('contains at least one invalid date format.'), + ), + )), + ); + }); + + testWithoutContext('throws an exception when adding formats and trailing plus sign', () { + expect( + () { + setupLocalizations({ + 'en': ''' +{ + "loggedIn": "Last logged in on {lastLoginDate}", + "@loggedIn": { + "placeholders": { + "lastLoginDate": { + "type": "DateTime", + "format": "yMd+Hm+" + } + } + } +}''' + }); + }, + throwsA(isA().having( + (L10nException e) => e.message, + 'message', + allOf( + contains('"yMd+Hm+"'), + contains('lastLoginDate'), + contains('contains at least one invalid date format.'), + ), + )), + ); + }); + testWithoutContext('throws an exception when no format attribute is passed in', () { expect( () { diff --git a/packages/flutter_tools/test/integration.shard/gen_l10n_test.dart b/packages/flutter_tools/test/integration.shard/gen_l10n_test.dart index 3567844e3d6..eb45762335f 100644 --- a/packages/flutter_tools/test/integration.shard/gen_l10n_test.dart +++ b/packages/flutter_tools/test/integration.shard/gen_l10n_test.dart @@ -136,45 +136,46 @@ void main() { '#l10n 75 (she)\n' '#l10n 76 (6/26/2023)\n' '#l10n 77 (5:23:00 AM)\n' - '#l10n 78 (--- es ---)\n' - '#l10n 79 (ES - Hello world)\n' - '#l10n 80 (ES - Hello _NEWLINE_ World)\n' - '#l10n 81 (ES - Hola \$ Mundo)\n' - '#l10n 82 (ES - Hello Mundo)\n' - '#l10n 83 (ES - Hola Mundo)\n' - '#l10n 84 (ES - Hello World on viernes, 1 de enero de 1960)\n' - '#l10n 85 (ES - Hello world argument on 1/1/1960 at 0:00)\n' - '#l10n 86 (ES - Hello World from 1960 to 2020)\n' - '#l10n 87 (ES - Hello for 123)\n' - '#l10n 88 (ES - Hello)\n' - '#l10n 89 (ES - Hello World)\n' - '#l10n 90 (ES - Hello two worlds)\n' - '#l10n 91 (ES - Hello)\n' - '#l10n 92 (ES - Hello nuevo World)\n' - '#l10n 93 (ES - Hello two nuevo worlds)\n' - '#l10n 94 (ES - Hello on viernes, 1 de enero de 1960)\n' - '#l10n 95 (ES - Hello World, on viernes, 1 de enero de 1960)\n' - '#l10n 96 (ES - Hello two worlds, on viernes, 1 de enero de 1960)\n' - '#l10n 97 (ES - Hello other 0 worlds, with a total of 100 citizens)\n' - '#l10n 98 (ES - Hello World of 101 citizens)\n' - '#l10n 99 (ES - Hello two worlds with 102 total citizens)\n' - '#l10n 100 (ES - [Hola] -Mundo- #123#)\n' - '#l10n 101 (ES - \$!)\n' - '#l10n 102 (ES - One \$)\n' - "#l10n 103 (ES - Flutter's amazing!)\n" - "#l10n 104 (ES - Flutter's amazing, times 2!)\n" - '#l10n 105 (ES - Flutter is "amazing"!)\n' - '#l10n 106 (ES - Flutter is "amazing", times 2!)\n' - '#l10n 107 (ES - 16 wheel truck)\n' - "#l10n 108 (ES - Sedan's elegance)\n" - '#l10n 109 (ES - Cabriolet has "acceleration")\n' - '#l10n 110 (ES - Oh, she found ES - 1 itemES - !)\n' - '#l10n 111 (ES - Indeed, ES - they like ES - Flutter!)\n' - '#l10n 112 (--- es_419 ---)\n' - '#l10n 113 (ES 419 - Hello World)\n' - '#l10n 114 (ES 419 - Hello)\n' - '#l10n 115 (ES 419 - Hello World)\n' - '#l10n 116 (ES 419 - Hello two worlds)\n' + '#l10n 78 (10/6/2024 11:29:48 PM and Tuesday, July 4, 2000 12:54:32 3rd quarter)\n' + '#l10n 79 (--- es ---)\n' + '#l10n 80 (ES - Hello world)\n' + '#l10n 81 (ES - Hello _NEWLINE_ World)\n' + '#l10n 82 (ES - Hola \$ Mundo)\n' + '#l10n 83 (ES - Hello Mundo)\n' + '#l10n 84 (ES - Hola Mundo)\n' + '#l10n 85 (ES - Hello World on viernes, 1 de enero de 1960)\n' + '#l10n 86 (ES - Hello world argument on 1/1/1960 at 0:00)\n' + '#l10n 87 (ES - Hello World from 1960 to 2020)\n' + '#l10n 88 (ES - Hello for 123)\n' + '#l10n 89 (ES - Hello)\n' + '#l10n 90 (ES - Hello World)\n' + '#l10n 91 (ES - Hello two worlds)\n' + '#l10n 92 (ES - Hello)\n' + '#l10n 93 (ES - Hello nuevo World)\n' + '#l10n 94 (ES - Hello two nuevo worlds)\n' + '#l10n 95 (ES - Hello on viernes, 1 de enero de 1960)\n' + '#l10n 96 (ES - Hello World, on viernes, 1 de enero de 1960)\n' + '#l10n 97 (ES - Hello two worlds, on viernes, 1 de enero de 1960)\n' + '#l10n 98 (ES - Hello other 0 worlds, with a total of 100 citizens)\n' + '#l10n 99 (ES - Hello World of 101 citizens)\n' + '#l10n 100 (ES - Hello two worlds with 102 total citizens)\n' + '#l10n 101 (ES - [Hola] -Mundo- #123#)\n' + '#l10n 102 (ES - \$!)\n' + '#l10n 103 (ES - One \$)\n' + "#l10n 104 (ES - Flutter's amazing!)\n" + "#l10n 105 (ES - Flutter's amazing, times 2!)\n" + '#l10n 106 (ES - Flutter is "amazing"!)\n' + '#l10n 107 (ES - Flutter is "amazing", times 2!)\n' + '#l10n 108 (ES - 16 wheel truck)\n' + "#l10n 109 (ES - Sedan's elegance)\n" + '#l10n 110 (ES - Cabriolet has "acceleration")\n' + '#l10n 111 (ES - Oh, she found ES - 1 itemES - !)\n' + '#l10n 112 (ES - Indeed, ES - they like ES - Flutter!)\n' + '#l10n 113 (--- es_419 ---)\n' + '#l10n 114 (ES 419 - Hello World)\n' + '#l10n 115 (ES 419 - Hello)\n' + '#l10n 116 (ES 419 - Hello World)\n' + '#l10n 117 (ES 419 - Hello two worlds)\n' '#l10n END\n' ); diff --git a/packages/flutter_tools/test/integration.shard/test_data/gen_l10n_project.dart b/packages/flutter_tools/test/integration.shard/test_data/gen_l10n_project.dart index 3f184bb2630..bee825e5f91 100644 --- a/packages/flutter_tools/test/integration.shard/test_data/gen_l10n_project.dart +++ b/packages/flutter_tools/test/integration.shard/test_data/gen_l10n_project.dart @@ -413,7 +413,21 @@ dependencies: } }, "datetime1": "{today, date, ::yMd}", - "datetime2": "{current, time, ::jms}" + "datetime2": "{current, time, ::jms}", + "datetimeAddedFormats": "{firstDate} and {secondDate}", + "@datetimeAddedFormats": { + "description": "A message with two dates, with added formats", + "placeholders": { + "firstDate": { + "type": "DateTime", + "format": "yMd+jms" + }, + "secondDate": { + "type": "DateTime", + "format": "yMMMMEEEEd+Hms+QQQQ" + } + } + } } '''; @@ -693,6 +707,7 @@ class Home extends StatelessWidget { "${localizations.selectInPlural('female', 1)}", '${localizations.datetime1(DateTime(2023, 6, 26))}', '${localizations.datetime2(DateTime(2023, 6, 26, 5, 23))}', + '${localizations.datetimeAddedFormats(DateTime(2024, 10, 6, 23, 29, 48), DateTime(2000, 7, 4, 12, 54, 32))}', ]); }, ), @@ -977,6 +992,7 @@ class Home extends StatelessWidget { "${localizations.selectInPlural(gender: 'female', count: 1)}", '${localizations.datetime1(today: DateTime(2023, 6, 26))}', '${localizations.datetime2(current: DateTime(2023, 6, 26, 5, 23))}', + '${localizations.datetimeAddedFormats(firstDate: DateTime(2024, 10, 6, 23, 29, 48), secondDate: DateTime(2000, 7, 4, 12, 54, 32))}', ]); }, ), From 79e8f450bf745b3cc55cb1c4beff74856bcb0a0a Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sat, 23 Nov 2024 16:41:38 -0500 Subject: [PATCH 196/386] Roll Flutter Engine from b382d17a27d1 to 7f160b9913d7 (2 revisions) (#159376) https://github.com/flutter/engine/compare/b382d17a27d1...7f160b9913d7 2024-11-23 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from D5CBHuB2c-v3Zai-c... to XOyk4KAUqAnkgC2WY... (flutter/engine#56775) 2024-11-23 skia-flutter-autoroll@skia.org Roll Skia from 6a3f77189dde to ded8ab47ee69 (1 revision) (flutter/engine#56774) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from D5CBHuB2c-v3 to XOyk4KAUqAnk If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index f7c03f2822f..3569642f96f 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -b382d17a27d13e38313f527ca0693d35ad670e8a +7f160b9913d78826b7e783edaf061bf7f8e8c0ef diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index c1583669965..afdab42b162 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -D5CBHuB2c-v3Zai-ctZfl5OU4d13Q1Af5LYFMrzdpVIC +XOyk4KAUqAnkgC2WYk1b5TuwpI9ODM4_pALKAH3QkCQC From 57d81129baf3d841f711b587f6f6170f81f8b585 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sun, 24 Nov 2024 00:38:25 -0500 Subject: [PATCH 197/386] Roll Flutter Engine from 7f160b9913d7 to 7231bf5799ae (1 revision) (#159381) https://github.com/flutter/engine/compare/7f160b9913d7...7231bf5799ae 2024-11-23 30870216+gaaclarke@users.noreply.github.com Smaller reactor handle locks (flutter/engine#56768) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 3569642f96f..d26970285a9 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -7f160b9913d78826b7e783edaf061bf7f8e8c0ef +7231bf5799aec539485dfe638f3fd24c34db6284 From 22ffc0b9358074579e0deeecccc3c761c0bf2dfa Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sun, 24 Nov 2024 05:06:39 -0500 Subject: [PATCH 198/386] Roll Flutter Engine from 7231bf5799ae to 37715e9cdcf8 (1 revision) (#159387) https://github.com/flutter/engine/compare/7231bf5799ae...37715e9cdcf8 2024-11-24 skia-flutter-autoroll@skia.org Roll Skia from ded8ab47ee69 to 01a3a55f1d54 (1 revision) (flutter/engine#56779) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index d26970285a9..3d566f04d8f 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -7231bf5799aec539485dfe638f3fd24c34db6284 +37715e9cdcf81246575d0a60418277ded3be71c8 From 59a8d9dc764a7d8fd5ddf28d9794338f8890dd7c Mon Sep 17 00:00:00 2001 From: Mohellebi abdessalem Date: Sun, 24 Nov 2024 17:54:18 +0100 Subject: [PATCH 199/386] fix failing lints in `aar_init_script.gradle` (#158025) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit android studio is marking those three imports as unused imports. ```gradle import org.gradle.api.Project import org.gradle.api.artifacts.Configuration import org.gradle.api.publish.maven.MavenPublication ``` the lint : ![Capture d’écran 2024-11-01 220654](https://github.com/user-attachments/assets/a152bf80-f3b4-4a6c-bdda-abfc6503d8ea) and this method could be converted to static : ```gradle String getFlutterRoot(Project project) { if (!project.hasProperty("flutter-root")) { throw new GradleException("The `-Pflutter-root` flag must be specified.") } return project.property("flutter-root") } ``` ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [ ] I updated/added relevant documentation (doc comments with `///`). - [ ] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- packages/flutter_tools/gradle/aar_init_script.gradle | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/packages/flutter_tools/gradle/aar_init_script.gradle b/packages/flutter_tools/gradle/aar_init_script.gradle index aa6bac1a39e..21918806764 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.") } From d1140638d4ff130cd18ee67dd501c6d8a8aec7c6 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sun, 24 Nov 2024 16:04:36 -0500 Subject: [PATCH 200/386] Roll Flutter Engine from 37715e9cdcf8 to 11777dcabe69 (1 revision) (#159401) https://github.com/flutter/engine/compare/37715e9cdcf8...11777dcabe69 2024-11-24 30870216+gaaclarke@users.noreply.github.com Cleaned up BufferBindingsGLES::BindUniformBuffer (flutter/engine#56777) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 3d566f04d8f..a4b29eccf4a 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -37715e9cdcf81246575d0a60418277ded3be71c8 +11777dcabe695c5df98fe62489be9c9fe0c621fb From 9bd2853737fff07a3819d752ef69bfac4c99048c Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sun, 24 Nov 2024 19:06:26 -0500 Subject: [PATCH 201/386] Roll Flutter Engine from 11777dcabe69 to 0ced389c842d (2 revisions) (#159403) https://github.com/flutter/engine/compare/11777dcabe69...0ced389c842d 2024-11-24 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from XOyk4KAUqAnkgC2WY... to 9o0fWa2xVhmxV6Mtn... (flutter/engine#56780) 2024-11-24 30870216+gaaclarke@users.noreply.github.com Replaces Resource's shared_ptr with unique_ptr (flutter/engine#56778) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from XOyk4KAUqAnk to 9o0fWa2xVhmx If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index a4b29eccf4a..ec66321d75e 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -11777dcabe695c5df98fe62489be9c9fe0c621fb +0ced389c842d4bc09f0138a1fb12a549b5c84fc9 diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index afdab42b162..3140e03baad 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -XOyk4KAUqAnkgC2WYk1b5TuwpI9ODM4_pALKAH3QkCQC +9o0fWa2xVhmxV6Mtn35w09_VsZcYWYbYelewc3wi2UYC From a0c3060c68d6f53970b6928f520f00128e2c122c Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Sun, 24 Nov 2024 21:34:37 -0500 Subject: [PATCH 202/386] Roll Flutter Engine from 0ced389c842d to ce1eb371eafa (1 revision) (#159404) https://github.com/flutter/engine/compare/0ced389c842d...ce1eb371eafa 2024-11-25 jason-simmons@users.noreply.github.com Fix the mapping from exit response strings to the FlPlatformChannelExitResponse enum (flutter/engine#56769) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index ec66321d75e..5874a712174 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -0ced389c842d4bc09f0138a1fb12a549b5c84fc9 +ce1eb371eafa791d3d25e5a031bfc47885859c4d From 8509d78734c5a6bb021a8cca82eed6f65b370b33 Mon Sep 17 00:00:00 2001 From: Bruno Leroux Date: Mon, 25 Nov 2024 14:09:32 +0100 Subject: [PATCH 203/386] Fix Date picker overlay colors aren't applied on selected state (#159203) ## Description This PR fixes the DatePicker overlay colors for the selected days. Before this PR, overlays were obscured by the selected day backgound. This fix simply replaces a DecoratedBox with an Ink to make the overlays visible. Combined with https://github.com/flutter/flutter/pull/159072 which fixes InkWell overlay color resolution related to the selected state, this PR fixes [Date picker overlay colors aren't applied on MaterialState.selected state](https://github.com/flutter/flutter/issues/130586). Before, no overlay visible for the selected day when hovered, focused, or pressed: https://github.com/user-attachments/assets/944d5035-68b2-40da-b606-3e8795229767 After, overlay is visible for the selected day when hovered, focused, or pressed (color change is slight as defined with M3 defaults): https://github.com/user-attachments/assets/2627955b-f45a-465f-8eb0-21955ccd8c3e ## Related Issue Fixes [Date picker overlay colors aren't applied on MaterialState.selected state](https://github.com/flutter/flutter/issues/130586). ## Tests Adds 12 tests. Updates several existing tests (those tests were looking for a `DecoratedBox`, make them look for an `Ink`). --- .../date_picker_theme_day_shape.0_test.dart | 27 +- .../src/material/calendar_date_picker.dart | 5 +- .../material/calendar_date_picker_test.dart | 2 +- .../test/material/date_picker_test.dart | 356 ++++++++++++++++-- .../test/material/date_picker_theme_test.dart | 29 +- 5 files changed, 365 insertions(+), 54 deletions(-) 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/packages/flutter/lib/src/material/calendar_date_picker.dart b/packages/flutter/lib/src/material/calendar_date_picker.dart index 6c96ec343ee..20f82a05d3b 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'; @@ -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/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/date_picker_test.dart b/packages/flutter/test/material/date_picker_test.dart index 380372d0390..810fa5e2cf2 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(); + }); }); } 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})), ); }); From cca41301f02b1c3cdd61dbcec6938102e748a8fa Mon Sep 17 00:00:00 2001 From: Taha Tesser Date: Mon, 25 Nov 2024 17:01:03 +0200 Subject: [PATCH 204/386] Update `image_filter_test` and `color_filter_test.dart` for Material 3 (#158985) Updated unit tests for `ColorFiltered` and `ImageFiltered` to have M2 and M3 versions. More info in #139076 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [ ] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [ ] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/wiki/Tree-hygiene#overview [Tree Hygiene]: https://github.com/flutter/flutter/wiki/Tree-hygiene [test-exempt]: https://github.com/flutter/flutter/wiki/Tree-hygiene#tests [Flutter Style Guide]: https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo [Features we expect every widget to implement]: https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/wiki/Tree-hygiene#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/wiki/Chat [Data Driven Fixes]: https://github.com/flutter/flutter/wiki/Data-driven-Fixes --- .../test/widgets/color_filter_test.dart | 43 ++++++++- .../test/widgets/image_filter_test.dart | 93 +++++++++++++++++-- 2 files changed, 125 insertions(+), 11 deletions(-) diff --git a/packages/flutter/test/widgets/color_filter_test.dart b/packages/flutter/test/widgets/color_filter_test.dart index 6ddb5892f95..0119afb7c99 100644 --- a/packages/flutter/test/widgets/color_filter_test.dart +++ b/packages/flutter/test/widgets/color_filter_test.dart @@ -30,8 +30,7 @@ void main() { ); }); - testWidgets('Color filter - sepia', (WidgetTester tester) async { - + testWidgets('Material2 - Color filter - sepia', (WidgetTester tester) async { const ColorFilter sepia = ColorFilter.matrix([ 0.39, 0.769, 0.189, 0, 0, // 0.349, 0.686, 0.168, 0, 0, // @@ -65,7 +64,45 @@ void main() { ); await expectLater( find.byType(ColorFiltered), - matchesGoldenFile('color_filter_sepia.png'), + matchesGoldenFile('color_filter_sepia_m2.png'), + ); + }, skip: impellerEnabled); // https://github.com/flutter/flutter/issues/143616 + + testWidgets('Color filter - sepia', (WidgetTester tester) async { + const ColorFilter sepia = ColorFilter.matrix([ + 0.39, 0.769, 0.189, 0, 0, // + 0.349, 0.686, 0.168, 0, 0, // + 0.272, 0.534, 0.131, 0, 0, // + 0, 0, 0, 1, 0, // + ]); + await tester.pumpWidget( + RepaintBoundary( + child: ColorFiltered( + colorFilter: sepia, + child: MaterialApp( + debugShowCheckedModeBanner: false, // https://github.com/flutter/flutter/issues/143616 + title: 'Flutter Demo', + theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue)), + home: Scaffold( + appBar: AppBar( + title: const Text('Sepia ColorFilter Test'), + ), + body: const Center( + child:Text('Hooray!'), + ), + floatingActionButton: FloatingActionButton( + onPressed: () { }, + tooltip: 'Increment', + child: const Icon(Icons.add), + ), + ), + ), + ), + ), + ); + await expectLater( + find.byType(ColorFiltered), + matchesGoldenFile('color_filter_sepia_m3.png'), ); }, skip: impellerEnabled); // https://github.com/flutter/flutter/issues/143616 diff --git a/packages/flutter/test/widgets/image_filter_test.dart b/packages/flutter/test/widgets/image_filter_test.dart index c92d04ca7b2..b2d37e85ca7 100644 --- a/packages/flutter/test/widgets/image_filter_test.dart +++ b/packages/flutter/test/widgets/image_filter_test.dart @@ -82,12 +82,12 @@ void main() { ); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/101874 - testWidgets('Image filter - matrix', (WidgetTester tester) async { + testWidgets('Material2 - Image filter - matrix', (WidgetTester tester) async { final ImageFilter matrix = ImageFilter.matrix(Float64List.fromList([ - 0.5, 0.0, 0.0, 0.0, // - 0.0, 0.5, 0.0, 0.0, // - 0.0, 0.0, 1.0, 0.0, // - 0.0, 0.0, 0.0, 1.0, // + 0.5, 0.0, 0.0, 0.0, + 0.0, 0.5, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0, ])); await tester.pumpWidget( RepaintBoundary( @@ -116,11 +116,49 @@ void main() { ); await expectLater( find.byType(ImageFiltered), - matchesGoldenFile('image_filter_matrix.png'), + matchesGoldenFile('image_filter_matrix_m2.png'), ); }); - testWidgets('Image filter - matrix with offset', (WidgetTester tester) async { + testWidgets('Image filter - matrix', (WidgetTester tester) async { + final ImageFilter matrix = ImageFilter.matrix(Float64List.fromList([ + 0.5, 0.0, 0.0, 0.0, + 0.0, 0.5, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0, + ])); + await tester.pumpWidget( + RepaintBoundary( + child: ImageFiltered( + imageFilter: matrix, + child: MaterialApp( + title: 'Flutter Demo', + theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue)), + debugShowCheckedModeBanner: false, // https://github.com/flutter/flutter/issues/143616 + home: Scaffold( + appBar: AppBar( + title: const Text('Matrix ImageFilter Test'), + ), + body: const Center( + child:Text('Hooray!'), + ), + floatingActionButton: FloatingActionButton( + onPressed: () { }, + tooltip: 'Increment', + child: const Icon(Icons.add), + ), + ), + ), + ), + ), + ); + await expectLater( + find.byType(ImageFiltered), + matchesGoldenFile('image_filter_matrix_m3.png'), + ); + }); + + testWidgets('Material2 - Image filter - matrix with offset', (WidgetTester tester) async { final Matrix4 matrix = Matrix4.rotationZ(pi / 18); final ImageFilter matrixFilter = ImageFilter.matrix(matrix.storage); final Key key = GlobalKey(); @@ -155,7 +193,46 @@ void main() { ); await expectLater( find.byKey(key), - matchesGoldenFile('image_filter_matrix_offset.png'), + matchesGoldenFile('image_filter_matrix_offset_m2.png'), + ); + }); + + testWidgets('Image filter - matrix with offset', (WidgetTester tester) async { + final Matrix4 matrix = Matrix4.rotationZ(pi / 18); + final ImageFilter matrixFilter = ImageFilter.matrix(matrix.storage); + final Key key = GlobalKey(); + await tester.pumpWidget( + RepaintBoundary( + key: key, + child: Transform.translate( + offset: const Offset(50, 50), + child: ImageFiltered( + imageFilter: matrixFilter, + child: MaterialApp( + title: 'Flutter Demo', + theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue)), + debugShowCheckedModeBanner: false, // https://github.com/flutter/flutter/issues/143616 + home: Scaffold( + appBar: AppBar( + title: const Text('Matrix ImageFilter Test'), + ), + body: const Center( + child:Text('Hooray!'), + ), + floatingActionButton: FloatingActionButton( + onPressed: () { }, + tooltip: 'Increment', + child: const Icon(Icons.add), + ), + ), + ), + ), + ), + ), + ); + await expectLater( + find.byKey(key), + matchesGoldenFile('image_filter_matrix_offset_m3.png'), ); }); From b5331b3e1b29768a517c6375b157ba7c93184c22 Mon Sep 17 00:00:00 2001 From: Ben Konyi Date: Mon, 25 Nov 2024 10:04:09 -0500 Subject: [PATCH 205/386] [ tool ] Fix expression evaluation not handling errors correctly (#159151) Also starts DDS for integration test devices. Fixes https://github.com/flutter/flutter/issues/157922 --- packages/flutter_tools/lib/src/compile.dart | 10 +- packages/flutter_tools/lib/src/run_hot.dart | 8 +- .../lib/src/test/flutter_platform.dart | 9 +- .../lib/src/test/flutter_tester_device.dart | 1 - .../lib/src/test/integration_test_device.dart | 17 ++- packages/flutter_tools/lib/src/vmservice.dart | 39 +++++- .../integration_test_device_test.dart | 22 ++++ .../expression_evaluation_test.dart | 122 +++++++++++------- 8 files changed, 166 insertions(+), 62 deletions(-) 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/run_hot.dart b/packages/flutter_tools/lib/src/run_hot.dart index 3d737c5913c..fcdf085b899 100644 --- a/packages/flutter_tools/lib/src/run_hot.dart +++ b/packages/flutter_tools/lib/src/run_hot.dart @@ -209,8 +209,12 @@ 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!); + } } } } diff --git a/packages/flutter_tools/lib/src/test/flutter_platform.dart b/packages/flutter_tools/lib/src/test/flutter_platform.dart index 6260cc9aa89..9e85534b1d4 100644 --- a/packages/flutter_tools/lib/src/test/flutter_platform.dart +++ b/packages/flutter_tools/lib/src/test/flutter_platform.dart @@ -27,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'; @@ -425,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'); } 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/vmservice.dart b/packages/flutter_tools/lib/src/vmservice.dart index bd02578ea87..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'; @@ -245,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)); } @@ -1072,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/test/general.shard/integration_test_device_test.dart b/packages/flutter_tools/test/general.shard/integration_test_device_test.dart index cf5e47b2c10..8cbcfbf3064 100644 --- a/packages/flutter_tools/test/general.shard/integration_test_device_test.dart +++ b/packages/flutter_tools/test/general.shard/integration_test_device_test.dart @@ -4,6 +4,7 @@ import 'package:file/file.dart'; import 'package:flutter_tools/src/application_package.dart'; +import 'package:flutter_tools/src/base/dds.dart'; import 'package:flutter_tools/src/base/io.dart' as io; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/build_info.dart'; @@ -19,6 +20,7 @@ import 'package:vm_service/vm_service.dart' as vm_service; import '../src/context.dart'; import '../src/fake_devices.dart'; import '../src/fake_vm_services.dart'; +import '../src/fakes.dart'; final vm_service.Isolate isolate = vm_service.Isolate( id: '1', @@ -64,6 +66,7 @@ final Uri vmServiceUri = Uri.parse('http://localhost:1234'); void main() { late FakeVmServiceHost fakeVmServiceHost; late TestDevice testDevice; + late DDSLauncherCallback originalDdsLauncher; setUp(() { testDevice = IntegrationTestTestDevice( @@ -103,6 +106,25 @@ void main() { }, ), ]); + + originalDdsLauncher = ddsLauncherCallback; + ddsLauncherCallback = ({ + required Uri remoteVmServiceUri, + Uri? serviceUri, + bool enableAuthCodes = true, + bool serveDevTools = false, + Uri? devToolsServerAddress, + bool enableServicePortFallback = false, + List cachedUserTags = const [], + String? dartExecutable, + String? google3WorkspaceRoot, + }) async { + return FakeDartDevelopmentServiceLauncher(uri: Uri.parse('http://localhost:1234')); + }; + }); + + tearDown(() { + ddsLauncherCallback = originalDdsLauncher; }); testUsingContext('will not start when package missing', () async { diff --git a/packages/flutter_tools/test/integration.shard/expression_evaluation_test.dart b/packages/flutter_tools/test/integration.shard/expression_evaluation_test.dart index 4676de1fac9..ac7de6cf5f9 100644 --- a/packages/flutter_tools/test/integration.shard/expression_evaluation_test.dart +++ b/packages/flutter_tools/test/integration.shard/expression_evaluation_test.dart @@ -18,16 +18,16 @@ void batch1() { late Directory tempDir; late FlutterRunTestDriver flutter; - Future initProject() async { + setUp(() async { tempDir = createResolvedTempDirectorySync('run_expression_eval_test.'); await project.setUpIn(tempDir); flutter = FlutterRunTestDriver(tempDir); - } + }); - Future cleanProject() async { + tearDown(() async { await flutter.stop(); tryToDelete(tempDir); - } + }); Future breakInBuildMethod(FlutterTestDriver flutter) async { await flutter.breakAt( @@ -43,52 +43,46 @@ void batch1() { ); } - testWithoutContext('flutter run expression evaluation - can evaluate trivial expressions in top level function', () async { - await initProject(); + testWithoutContext('can evaluate trivial expressions in top level function', () async { await flutter.run(withDebugger: true); await breakInTopLevelFunction(flutter); await evaluateTrivialExpressions(flutter); - await cleanProject(); }); - testWithoutContext('flutter run expression evaluation - can evaluate trivial expressions in build method', () async { - await initProject(); + testWithoutContext('can evaluate trivial expressions in build method', () async { await flutter.run(withDebugger: true); await breakInBuildMethod(flutter); await evaluateTrivialExpressions(flutter); - await cleanProject(); }); - testWithoutContext('flutter run expression evaluation - can evaluate complex expressions in top level function', () async { - await initProject(); + testWithoutContext('can evaluate complex expressions in top level function', () async { await flutter.run(withDebugger: true); await breakInTopLevelFunction(flutter); await evaluateComplexExpressions(flutter); - await cleanProject(); }); - testWithoutContext('flutter run expression evaluation - can evaluate complex expressions in build method', () async { - await initProject(); + testWithoutContext('can evaluate complex expressions in build method', () async { await flutter.run(withDebugger: true); await breakInBuildMethod(flutter); await evaluateComplexExpressions(flutter); - await cleanProject(); }); - testWithoutContext('flutter run expression evaluation - can evaluate expressions returning complex objects in top level function', () async { - await initProject(); + testWithoutContext('can evaluate expressions returning complex objects in top level function', () async { await flutter.run(withDebugger: true); await breakInTopLevelFunction(flutter); await evaluateComplexReturningExpressions(flutter); - await cleanProject(); }); - testWithoutContext('flutter run expression evaluation - can evaluate expressions returning complex objects in build method', () async { - await initProject(); + testWithoutContext('can evaluate expressions returning complex objects in build method', () async { await flutter.run(withDebugger: true); await breakInBuildMethod(flutter); await evaluateComplexReturningExpressions(flutter); - await cleanProject(); + }); + + testWithoutContext('evaluating invalid expressions throws an exception with compilation error details', () async { + await flutter.run(withDebugger: true); + await breakInTopLevelFunction(flutter); + await evaluateInvalidExpression(flutter); }); } @@ -97,19 +91,18 @@ void batch2() { late Directory tempDir; late FlutterTestTestDriver flutter; - Future initProject() async { + setUp(() async { tempDir = createResolvedTempDirectorySync('test_expression_eval_test.'); await project.setUpIn(tempDir); flutter = FlutterTestTestDriver(tempDir); - } + }); - Future cleanProject() async { + tearDown(() async { await flutter.waitForCompletion(); tryToDelete(tempDir); - } + }); - testWithoutContext('flutter test expression evaluation - can evaluate trivial expressions in a test', () async { - await initProject(); + testWithoutContext('can evaluate trivial expressions in a test', () async { await flutter.test( withDebugger: true, beforeStart: () => flutter.addBreakpoint(project.breakpointUri, project.breakpointLine), @@ -121,30 +114,33 @@ void batch2() { // https://github.com/Dart-Code/Dart-Code/issues/4243. final String dillFilename = '${project.testFilePath}.dill'; expect(fileSystem.file(dillFilename).existsSync(), isFalse); - - await cleanProject(); }); - testWithoutContext('flutter test expression evaluation - can evaluate complex expressions in a test', () async { - await initProject(); + testWithoutContext('can evaluate complex expressions in a test', () async { await flutter.test( withDebugger: true, beforeStart: () => flutter.addBreakpoint(project.breakpointUri, project.breakpointLine), ); await flutter.waitForPause(); await evaluateComplexExpressions(flutter); - await cleanProject(); }); - testWithoutContext('flutter test expression evaluation - can evaluate expressions returning complex objects in a test', () async { - await initProject(); + testWithoutContext('can evaluate expressions returning complex objects in a test', () async { await flutter.test( withDebugger: true, beforeStart: () => flutter.addBreakpoint(project.breakpointUri, project.breakpointLine), ); await flutter.waitForPause(); await evaluateComplexReturningExpressions(flutter); - await cleanProject(); + }); + + testWithoutContext('evaluating invalid expressions throws an exception with compilation error details', () async { + await flutter.test( + withDebugger: true, + beforeStart: () => flutter.addBreakpoint(project.breakpointUri, project.breakpointLine), + ); + await flutter.waitForPause(); + await evaluateInvalidExpression(flutter); }); } @@ -153,19 +149,18 @@ void batch3() { late Directory tempDir; late FlutterTestTestDriver flutter; - Future initProject() async { + setUp(() async { tempDir = createResolvedTempDirectorySync('integration_test_expression_eval_test.'); await project.setUpIn(tempDir); flutter = FlutterTestTestDriver(tempDir); - } + }); - Future cleanProject() async { + tearDown(() async { await flutter.waitForCompletion(); tryToDelete(tempDir); - } + }); - testWithoutContext('flutter integration test expression evaluation - can evaluate expressions in a test', () async { - await initProject(); + testWithoutContext('can evaluate expressions in a test', () async { await flutter.test( deviceId: 'flutter-tester', testFile: project.testFilePath, @@ -179,10 +174,23 @@ void batch3() { // https://github.com/Dart-Code/Dart-Code/issues/4243. final String dillFilename = '${project.testFilePath}.dill'; expect(fileSystem.file(dillFilename).existsSync(), isFalse); - - await cleanProject(); }); + testWithoutContext('evaluating invalid expressions throws an exception with compilation error details', () async { + await flutter.test( + deviceId: 'flutter-tester', + testFile: project.testFilePath, + withDebugger: true, + beforeStart: () => flutter.addBreakpoint(project.breakpointUri, project.breakpointLine), + ); + await flutter.waitForPause(); + await evaluateInvalidExpression(flutter); + + // Ensure we did not leave a dill file alongside the test. + // https://github.com/Dart-Code/Dart-Code/issues/4243. + final String dillFilename = '${project.testFilePath}.dill'; + expect(fileSystem.file(dillFilename).existsSync(), isFalse); + }); } Future evaluateTrivialExpressions(FlutterTestDriver flutter) async { @@ -211,6 +219,26 @@ Future evaluateComplexReturningExpressions(FlutterTestDriver flutter) asyn expectValue(res, '${date.year}-${date.month}-${date.day}'); } +Future evaluateInvalidExpression(FlutterTestDriver flutter) async { + try { + await flutter.evaluateInFrame('is Foo'); + fail("'is Foo' is not a valid expression"); + } on RPCError catch (e) { + expect(e.code, RPCErrorKind.kExpressionCompilationError.code); + expect(e.message, RPCErrorKind.kExpressionCompilationError.message); + expect( + e.details, + "org-dartlang-debug:synthetic_debug_expression:1:1: Error: Expected an identifier, but got 'is'.\n" + "Try inserting an identifier before 'is'.\n" + 'is Foo\n' + '^^\n' + "org-dartlang-debug:synthetic_debug_expression:1:4: Error: 'Foo' isn't a type.\n" + 'is Foo\n' + ' ^^^\n', + ); + } +} + void expectInstanceOfClass(ObjRef result, String name) { expect(result, const TypeMatcher() @@ -231,7 +259,7 @@ void expectValue(ObjRef result, String message) { } void main() { - batch1(); - batch2(); - batch3(); + group('flutter run expression evaluation -', batch1); + group('flutter test expression evaluation -', batch2); + group('flutter integration test expression evaluation -', batch3); } From d527f6ee10ae104f7dae5426c56ab337fc62df03 Mon Sep 17 00:00:00 2001 From: userFortyTwo <85737538+userFortyTwo@users.noreply.github.com> Date: Mon, 25 Nov 2024 16:05:03 +0100 Subject: [PATCH 206/386] Fix typo in gen_l10n_types.dart (#159035) This pull request fixes a typo. --- .../flutter_tools/lib/src/localizations/gen_l10n_types.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 e62b8904098..6cea9c6b6a9 100644 --- a/packages/flutter_tools/lib/src/localizations/gen_l10n_types.dart +++ b/packages/flutter_tools/lib/src/localizations/gen_l10n_types.dart @@ -639,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' ); From 7b9f853cc72ef0c29e63e8c99bf0bf75849895b9 Mon Sep 17 00:00:00 2001 From: LongCatIsLooong <31859944+LongCatIsLooong@users.noreply.github.com> Date: Mon, 25 Nov 2024 11:20:31 -0800 Subject: [PATCH 207/386] Fix a failing test missed in #159108 (#159407) Missed this test in https://github.com/flutter/flutter/pull/159108 ## Pre-launch Checklist - [ ] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [ ] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [ ] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [ ] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [ ] I updated/added relevant documentation (doc comments with `///`). - [ ] I added new tests to check the change I am making, or this PR is [test-exempt]. - [ ] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [ ] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- packages/flutter/test/widgets/custom_painter_test.dart | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/flutter/test/widgets/custom_painter_test.dart b/packages/flutter/test/widgets/custom_painter_test.dart index af165401282..c27317e1caf 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 + ..removeWhere((SemanticsAction action) => action.index == 1 << 23); const int expectedId = 2; final TestSemantics expectedSemantics = TestSemantics.root( From 3d896d8743696be3ec262c36381f386a36fea57c Mon Sep 17 00:00:00 2001 From: "auto-submit[bot]" <98614782+auto-submit[bot]@users.noreply.github.com> Date: Mon, 25 Nov 2024 12:47:13 -0800 Subject: [PATCH 208/386] Reverts "Update `image_filter_test` and `color_filter_test.dart` for Material 3 (#158985)" (#159437) Reverts: flutter/flutter#158985 Initiated by: QuncCccccc Reason for reverting: to unblock tree Original PR Author: TahaTesser Reviewed By: {QuncCccccc} This change reverts the following previous change: Updated unit tests for `ColorFiltered` and `ImageFiltered` to have M2 and M3 versions. More info in #139076 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [ ] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [ ] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/wiki/Tree-hygiene#overview [Tree Hygiene]: https://github.com/flutter/flutter/wiki/Tree-hygiene [test-exempt]: https://github.com/flutter/flutter/wiki/Tree-hygiene#tests [Flutter Style Guide]: https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo [Features we expect every widget to implement]: https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/wiki/Tree-hygiene#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/wiki/Chat [Data Driven Fixes]: https://github.com/flutter/flutter/wiki/Data-driven-Fixes Co-authored-by: auto-submit[bot] --- .../test/widgets/color_filter_test.dart | 43 +-------- .../test/widgets/image_filter_test.dart | 93 ++----------------- 2 files changed, 11 insertions(+), 125 deletions(-) diff --git a/packages/flutter/test/widgets/color_filter_test.dart b/packages/flutter/test/widgets/color_filter_test.dart index 0119afb7c99..6ddb5892f95 100644 --- a/packages/flutter/test/widgets/color_filter_test.dart +++ b/packages/flutter/test/widgets/color_filter_test.dart @@ -30,7 +30,8 @@ void main() { ); }); - testWidgets('Material2 - Color filter - sepia', (WidgetTester tester) async { + testWidgets('Color filter - sepia', (WidgetTester tester) async { + const ColorFilter sepia = ColorFilter.matrix([ 0.39, 0.769, 0.189, 0, 0, // 0.349, 0.686, 0.168, 0, 0, // @@ -64,45 +65,7 @@ void main() { ); await expectLater( find.byType(ColorFiltered), - matchesGoldenFile('color_filter_sepia_m2.png'), - ); - }, skip: impellerEnabled); // https://github.com/flutter/flutter/issues/143616 - - testWidgets('Color filter - sepia', (WidgetTester tester) async { - const ColorFilter sepia = ColorFilter.matrix([ - 0.39, 0.769, 0.189, 0, 0, // - 0.349, 0.686, 0.168, 0, 0, // - 0.272, 0.534, 0.131, 0, 0, // - 0, 0, 0, 1, 0, // - ]); - await tester.pumpWidget( - RepaintBoundary( - child: ColorFiltered( - colorFilter: sepia, - child: MaterialApp( - debugShowCheckedModeBanner: false, // https://github.com/flutter/flutter/issues/143616 - title: 'Flutter Demo', - theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue)), - home: Scaffold( - appBar: AppBar( - title: const Text('Sepia ColorFilter Test'), - ), - body: const Center( - child:Text('Hooray!'), - ), - floatingActionButton: FloatingActionButton( - onPressed: () { }, - tooltip: 'Increment', - child: const Icon(Icons.add), - ), - ), - ), - ), - ), - ); - await expectLater( - find.byType(ColorFiltered), - matchesGoldenFile('color_filter_sepia_m3.png'), + matchesGoldenFile('color_filter_sepia.png'), ); }, skip: impellerEnabled); // https://github.com/flutter/flutter/issues/143616 diff --git a/packages/flutter/test/widgets/image_filter_test.dart b/packages/flutter/test/widgets/image_filter_test.dart index b2d37e85ca7..c92d04ca7b2 100644 --- a/packages/flutter/test/widgets/image_filter_test.dart +++ b/packages/flutter/test/widgets/image_filter_test.dart @@ -82,12 +82,12 @@ void main() { ); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/101874 - testWidgets('Material2 - Image filter - matrix', (WidgetTester tester) async { + testWidgets('Image filter - matrix', (WidgetTester tester) async { final ImageFilter matrix = ImageFilter.matrix(Float64List.fromList([ - 0.5, 0.0, 0.0, 0.0, - 0.0, 0.5, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, + 0.5, 0.0, 0.0, 0.0, // + 0.0, 0.5, 0.0, 0.0, // + 0.0, 0.0, 1.0, 0.0, // + 0.0, 0.0, 0.0, 1.0, // ])); await tester.pumpWidget( RepaintBoundary( @@ -116,49 +116,11 @@ void main() { ); await expectLater( find.byType(ImageFiltered), - matchesGoldenFile('image_filter_matrix_m2.png'), + matchesGoldenFile('image_filter_matrix.png'), ); }); - testWidgets('Image filter - matrix', (WidgetTester tester) async { - final ImageFilter matrix = ImageFilter.matrix(Float64List.fromList([ - 0.5, 0.0, 0.0, 0.0, - 0.0, 0.5, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - ])); - await tester.pumpWidget( - RepaintBoundary( - child: ImageFiltered( - imageFilter: matrix, - child: MaterialApp( - title: 'Flutter Demo', - theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue)), - debugShowCheckedModeBanner: false, // https://github.com/flutter/flutter/issues/143616 - home: Scaffold( - appBar: AppBar( - title: const Text('Matrix ImageFilter Test'), - ), - body: const Center( - child:Text('Hooray!'), - ), - floatingActionButton: FloatingActionButton( - onPressed: () { }, - tooltip: 'Increment', - child: const Icon(Icons.add), - ), - ), - ), - ), - ), - ); - await expectLater( - find.byType(ImageFiltered), - matchesGoldenFile('image_filter_matrix_m3.png'), - ); - }); - - testWidgets('Material2 - Image filter - matrix with offset', (WidgetTester tester) async { + testWidgets('Image filter - matrix with offset', (WidgetTester tester) async { final Matrix4 matrix = Matrix4.rotationZ(pi / 18); final ImageFilter matrixFilter = ImageFilter.matrix(matrix.storage); final Key key = GlobalKey(); @@ -193,46 +155,7 @@ void main() { ); await expectLater( find.byKey(key), - matchesGoldenFile('image_filter_matrix_offset_m2.png'), - ); - }); - - testWidgets('Image filter - matrix with offset', (WidgetTester tester) async { - final Matrix4 matrix = Matrix4.rotationZ(pi / 18); - final ImageFilter matrixFilter = ImageFilter.matrix(matrix.storage); - final Key key = GlobalKey(); - await tester.pumpWidget( - RepaintBoundary( - key: key, - child: Transform.translate( - offset: const Offset(50, 50), - child: ImageFiltered( - imageFilter: matrixFilter, - child: MaterialApp( - title: 'Flutter Demo', - theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue)), - debugShowCheckedModeBanner: false, // https://github.com/flutter/flutter/issues/143616 - home: Scaffold( - appBar: AppBar( - title: const Text('Matrix ImageFilter Test'), - ), - body: const Center( - child:Text('Hooray!'), - ), - floatingActionButton: FloatingActionButton( - onPressed: () { }, - tooltip: 'Increment', - child: const Icon(Icons.add), - ), - ), - ), - ), - ), - ), - ); - await expectLater( - find.byKey(key), - matchesGoldenFile('image_filter_matrix_offset_m3.png'), + matchesGoldenFile('image_filter_matrix_offset.png'), ); }); From 70e31b48bf81c182d2aa0990f78cd28114e85cf2 Mon Sep 17 00:00:00 2001 From: Gray Mackall <34871572+gmackall@users.noreply.github.com> Date: Mon, 25 Nov 2024 13:13:24 -0800 Subject: [PATCH 209/386] Bump AGP/Gradle/Kotlin warn versions (#158839) Bumps the versions up a bit, so we can keep people moving forward. ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --------- Co-authored-by: Gray Mackall --- .../src/main/kotlin/dependency_version_checker.gradle.kts | 6 +++--- .../android_dependency_version_checking_test.dart | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) 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/test/android_java11_integration.shard/android_dependency_version_checking_test.dart b/packages/flutter_tools/test/android_java11_integration.shard/android_dependency_version_checking_test.dart index 97fe9839ade..547b3c36e21 100644 --- a/packages/flutter_tools/test/android_java11_integration.shard/android_dependency_version_checking_test.dart +++ b/packages/flutter_tools/test/android_java11_integration.shard/android_dependency_version_checking_test.dart @@ -30,7 +30,7 @@ void main() { testUsingContext( 'AGP version out of "warn" support band but in "error" band builds ' 'successfully and prints warning', () async { - final VersionTuple versionTuple = VersionTuple(agpVersion: '7.0.0', gradleVersion: '7.5', kotlinVersion: '1.7.10', compileSdkVersion: '34'); + final VersionTuple versionTuple = VersionTuple(agpVersion: '7.3.0', gradleVersion: '7.5', kotlinVersion: '1.7.10', compileSdkVersion: '34'); final ProcessResult result = await buildFlutterApkWithSpecifiedDependencyVersions( versions: versionTuple, tempDir: tempDir @@ -43,7 +43,7 @@ void main() { 'Gradle version out of "warn" support band but in "error" band builds ' 'successfully and prints warning', () async { // Create a new flutter project. - final VersionTuple versionTuple = VersionTuple(agpVersion: '7.0.0', gradleVersion: '7.0.2', kotlinVersion: '1.7.10', compileSdkVersion: '34'); + final VersionTuple versionTuple = VersionTuple(agpVersion: '7.3.0', gradleVersion: '7.4.1', kotlinVersion: '1.7.10', compileSdkVersion: '34'); final ProcessResult result = await buildFlutterApkWithSpecifiedDependencyVersions( versions: versionTuple, tempDir: tempDir @@ -55,7 +55,7 @@ void main() { testUsingContext( 'Kotlin version out of "warn" support band but in "error" band builds ' 'successfully and prints warning', () async { - final VersionTuple versionTuple = VersionTuple(agpVersion: '7.4.0', gradleVersion: '7.5', kotlinVersion: '1.7.0', compileSdkVersion: '34'); + final VersionTuple versionTuple = VersionTuple(agpVersion: '7.4.0', gradleVersion: '7.5', kotlinVersion: '1.8.0', compileSdkVersion: '34'); final ProcessResult result = await buildFlutterApkWithSpecifiedDependencyVersions( versions: versionTuple, tempDir: tempDir From 756cf306d68b48bf911f824aa70262abb0a14946 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Mon, 25 Nov 2024 16:14:43 -0500 Subject: [PATCH 210/386] Roll Flutter Engine from ce1eb371eafa to fe45a6608651 (4 revisions) (#159435) https://github.com/flutter/engine/compare/ce1eb371eafa...fe45a6608651 2024-11-25 34871572+gmackall@users.noreply.github.com Bump versions of agp and robolectric, and configure to use SDK 35 (flutter/engine#56732) 2024-11-25 jiahaog@users.noreply.github.com Add missing import for malloc (flutter/engine#56781) 2024-11-25 skia-flutter-autoroll@skia.org Roll Skia from 7588789d8fc6 to 12c8bd6ac1d9 (1 revision) (flutter/engine#56786) 2024-11-25 skia-flutter-autoroll@skia.org Roll Skia from 01a3a55f1d54 to 7588789d8fc6 (2 revisions) (flutter/engine#56784) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 5874a712174..ffd5c010764 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -ce1eb371eafa791d3d25e5a031bfc47885859c4d +fe45a6608651e249e1b54a6379b593b587934b20 From 1a2d6a30bca2476c91dd01cd67405443cfc251d3 Mon Sep 17 00:00:00 2001 From: chunhtai <47866232+chunhtai@users.noreply.github.com> Date: Mon, 25 Nov 2024 13:21:04 -0800 Subject: [PATCH 211/386] Framework sends a11y message when enabling semantics (#159163) fixes https://github.com/flutter/flutter/issues/158399 engine ios https://github.com/flutter/engine/pull/56691 ## Pre-launch Checklist - [ ] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [ ] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [ ] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [ ] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [ ] I updated/added relevant documentation (doc comments with `///`). - [ ] I added new tests to check the change I am making, or this PR is [test-exempt]. - [ ] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [ ] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- .../flutter/lib/src/rendering/binding.dart | 10 +++++ .../lib/src/semantics/semantics_event.dart | 34 ++++++++++++++++ ...ipeline_manifold_semantics_event_test.dart | 39 +++++++++++++++++++ .../flutter/test/widgets/feedback_test.dart | 7 ++-- .../test/src/real_tests/extension_test.dart | 10 ++--- 5 files changed, 92 insertions(+), 8 deletions(-) create mode 100644 packages/flutter/test/rendering/binding_pipeline_manifold_semantics_event_test.dart diff --git a/packages/flutter/lib/src/rendering/binding.dart b/packages/flutter/lib/src/rendering/binding.dart index f54d4a8f6cf..15cf986da55 100644 --- a/packages/flutter/lib/src/rendering/binding.dart +++ b/packages/flutter/lib/src/rendering/binding.dart @@ -790,10 +790,20 @@ class _BindingPipelineManifold extends ChangeNotifier implements PipelineManifol ChangeNotifier.maybeDispatchObjectCreation(this); } _binding.addSemanticsEnabledListener(notifyListeners); + if (_binding.semanticsEnabled) { + SystemChannels.accessibility.send(const GeneratingSemanticsTreeSemanticsEvent(true).toMap()); + } } final RendererBinding _binding; + @protected + @override + void notifyListeners() { + SystemChannels.accessibility.send(GeneratingSemanticsTreeSemanticsEvent(_binding.semanticsEnabled).toMap()); + super.notifyListeners(); + } + @override void requestVisualUpdate() { _binding.ensureVisualUpdate(); diff --git a/packages/flutter/lib/src/semantics/semantics_event.dart b/packages/flutter/lib/src/semantics/semantics_event.dart index b3751ea6c35..5e17fdfb1c4 100644 --- a/packages/flutter/lib/src/semantics/semantics_event.dart +++ b/packages/flutter/lib/src/semantics/semantics_event.dart @@ -135,6 +135,40 @@ class TooltipSemanticsEvent extends SemanticsEvent { } } +/// An event to notify native OS that flutter starts or stops the semantics tree +/// generation +/// +/// The [generating] indicate whether flutter starts generating the semantics +/// tree. If true, flutter will start sending semantics update to platform +/// embedding. +/// +/// Embeddings must be ready to receive semantics update after they receive this +/// event with [generating] set to true as framework will start sending +/// semantics update in the next frame. +/// +/// If [generating] is false, embeddings need to clean up previous updates as +/// the framework semantics tree was completely destroyed. +class GeneratingSemanticsTreeSemanticsEvent extends SemanticsEvent { + + /// Constructs an event that notify platform whether it is generating + /// semantics tree. + const GeneratingSemanticsTreeSemanticsEvent(this.generating) + : super('generatingSemanticsTree'); + + /// Whether framework starts generating the semantics tree. + /// + /// If true, flutter starts sending semantics update to platform + /// embedding. + final bool generating; + + @override + Map getDataMap() { + return { + 'generating': generating, + }; + } +} + /// An event which triggers long press semantic feedback. /// /// Currently only honored on Android. Triggers a long-press specific sound diff --git a/packages/flutter/test/rendering/binding_pipeline_manifold_semantics_event_test.dart b/packages/flutter/test/rendering/binding_pipeline_manifold_semantics_event_test.dart new file mode 100644 index 00000000000..b4e20b64058 --- /dev/null +++ b/packages/flutter/test/rendering/binding_pipeline_manifold_semantics_event_test.dart @@ -0,0 +1,39 @@ +// 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/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'rendering_tester.dart'; + +void main() { + test('Turning global semantics on/off sends semantics event', () { + TestRenderingFlutterBinding.ensureInitialized(); + final List messages = []; + TestRenderingFlutterBinding.instance.defaultBinaryMessenger.setMockDecodedMessageHandler( + SystemChannels.accessibility, + (dynamic message) async { + messages.add(message); + } + ); + final SemanticsHandle handle = TestRenderingFlutterBinding.instance.ensureSemantics(); + expect(messages.length, 1); + expect(messages[0], { + 'type': 'generatingSemanticsTree', + 'data': { + 'generating': true, + }, + }); + + handle.dispose(); + expect(messages.length, 2); + expect(messages[1], { + 'type': 'generatingSemanticsTree', + 'data': { + 'generating': false, + }, + }); + TestRenderingFlutterBinding.instance.defaultBinaryMessenger.setMockDecodedMessageHandler(SystemChannels.accessibility, null); + }); +} diff --git a/packages/flutter/test/widgets/feedback_test.dart b/packages/flutter/test/widgets/feedback_test.dart index e66bcc21ad6..40584f648d2 100644 --- a/packages/flutter/test/widgets/feedback_test.dart +++ b/packages/flutter/test/widgets/feedback_test.dart @@ -38,7 +38,7 @@ void main () { testWidgets('forTap', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); - + semanticEvents.clear(); await tester.pumpWidget(TestWidget( tapHandler: (BuildContext context) { return () => Feedback.forTap(context); @@ -67,7 +67,7 @@ void main () { testWidgets('forTap Wrapper', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); - + semanticEvents.clear(); int callbackCount = 0; void callback() { callbackCount++; @@ -102,7 +102,7 @@ void main () { testWidgets('forLongPress', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); - + semanticEvents.clear(); await tester.pumpWidget(TestWidget( longPressHandler: (BuildContext context) { return () => Feedback.forLongPress(context); @@ -130,6 +130,7 @@ void main () { testWidgets('forLongPress Wrapper', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); + semanticEvents.clear(); int callbackCount = 0; void callback() { callbackCount++; diff --git a/packages/flutter_driver/test/src/real_tests/extension_test.dart b/packages/flutter_driver/test/src/real_tests/extension_test.dart index 5ea63965717..27f2a7c585b 100644 --- a/packages/flutter_driver/test/src/real_tests/extension_test.dart +++ b/packages/flutter_driver/test/src/real_tests/extension_test.dart @@ -280,7 +280,7 @@ void main() { 'response': {}, }, ); - }); + }, semanticsEnabled: false); // Disabling semantics to prevent the unexpected message. testWidgets( 'waiting for NoPendingPlatformMessages returns until a single method channel call returns', (WidgetTester tester) async { @@ -313,7 +313,7 @@ void main() { 'response': {}, }, ); - }); + }, semanticsEnabled: false); // Disabling semantics to prevent the unexpected message. testWidgets( 'waiting for NoPendingPlatformMessages returns until both method channel calls return', (WidgetTester tester) async { @@ -362,7 +362,7 @@ void main() { 'response': {}, }, ); - }); + }, semanticsEnabled: false); // Disabling semantics to prevent the unexpected message. testWidgets( 'waiting for NoPendingPlatformMessages returns until new method channel call returns', (WidgetTester tester) async { @@ -413,7 +413,7 @@ void main() { 'response': {}, }, ); - }); + }, semanticsEnabled: false); // Disabling semantics to prevent the unexpected message. testWidgets( 'waiting for NoPendingPlatformMessages returns until both old and new method channel calls return', (WidgetTester tester) async { @@ -463,7 +463,7 @@ void main() { 'response': {}, }, ); - }); + }, semanticsEnabled: false); // Disabling semantics to prevent the unexpected message. }); group('getSemanticsId', () { From 7be361cd6ab5f60a1ca785bc399c4a9f5e3bd185 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Mon, 25 Nov 2024 16:25:03 -0500 Subject: [PATCH 212/386] Roll Packages from 920321356e45 to 46aeb2b29d60 (3 revisions) (#159420) https://github.com/flutter/packages/compare/920321356e45...46aeb2b29d60 2024-11-22 reidbaker@google.com Update avd_cipd_version (flutter/packages#8135) 2024-11-22 10687576+bparrishMines@users.noreply.github.com [interactive_media_ads] Adds internal wrapper for Android native `CompanionAdSlot` and `CompanionAdSlot.ClickListener` (flutter/packages#8131) 2024-11-22 engine-flutter-autoroll@skia.org Roll Flutter from 93d772c5cdd8 to 793569f621f7 (5 revisions) (flutter/packages#8152) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-packages-flutter-autoroll Please CC flutter-ecosystem@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/flutter_packages.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/flutter_packages.version b/bin/internal/flutter_packages.version index f5fbdfef09e..7fa1d4bcd18 100644 --- a/bin/internal/flutter_packages.version +++ b/bin/internal/flutter_packages.version @@ -1 +1 @@ -920321356e4507f1471bb00413d84b846a3c2697 +46aeb2b29d60d3b0492b716baaeed4c803890078 From 85632156c5aec75b89029f37c57d8031ae6b474c Mon Sep 17 00:00:00 2001 From: chunhtai <47866232+chunhtai@users.noreply.github.com> Date: Mon, 25 Nov 2024 13:37:10 -0800 Subject: [PATCH 213/386] Reland "Set stable color for semantics debugger (#157884)" (#159355) This reverts commit 07690a69b0067f8a8471470f7314a3294591033d. previous pr was merged when tree is close by mistake, and was revert out of precaution. There is no change in this reland. ## Pre-launch Checklist - [ ] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [ ] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [ ] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [ ] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [ ] I updated/added relevant documentation (doc comments with `///`). - [ ] I added new tests to check the change I am making, or this PR is [test-exempt]. - [ ] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [ ] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- .../flutter/lib/src/semantics/semantics.dart | 3 +-- .../lib/src/widgets/semantics_debugger.dart | 26 ++++++++++++++++--- .../test/widgets/semantics_debugger_test.dart | 20 ++++++++++++++ 3 files changed, 43 insertions(+), 6 deletions(-) diff --git a/packages/flutter/lib/src/semantics/semantics.dart b/packages/flutter/lib/src/semantics/semantics.dart index 1934aa2b80c..2df357ee82b 100644 --- a/packages/flutter/lib/src/semantics/semantics.dart +++ b/packages/flutter/lib/src/semantics/semantics.dart @@ -2092,8 +2092,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!) { 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/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(); From 0896292e35e5963788974f4a8857be826e025b73 Mon Sep 17 00:00:00 2001 From: Matthias Ngeo Date: Tue, 26 Nov 2024 06:54:53 +0800 Subject: [PATCH 214/386] Refactor bottom sheet & related widgets (#159257) This PR refactors Material's bottom sheet & related widgets. It also replaces internal usage of deprecated types such as `MaterialState` with `WidgetState`. ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [ ] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [ ] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- .../lib/src/material/bottom_sheet.dart | 93 ++++++------------- 1 file changed, 30 insertions(+), 63 deletions(-) diff --git a/packages/flutter/lib/src/material/bottom_sheet.dart b/packages/flutter/lib/src/material/bottom_sheet.dart index 9dfeec84cfb..735551f9927 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; @@ -1137,11 +1104,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 ); From 6494c0b5c4b58ceb2b1d5a23331b792105376ed9 Mon Sep 17 00:00:00 2001 From: Michael Goderbauer Date: Mon, 25 Nov 2024 15:00:03 -0800 Subject: [PATCH 215/386] Update comment in analysis_options.yaml (#159449) --- analysis_options.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/analysis_options.yaml b/analysis_options.yaml index e613f771da4..8a4a51abafc 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -219,7 +219,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 From 37bda37c385abb195677a35e853f8b9e929a065e Mon Sep 17 00:00:00 2001 From: Michael Goderbauer Date: Mon, 25 Nov 2024 15:16:33 -0800 Subject: [PATCH 216/386] Roll dartdoc to 8.3.0 (#159448) --- dev/bots/docs.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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. From 4051a38dd768b96e4e0f43a8a81e152961b68a56 Mon Sep 17 00:00:00 2001 From: Elliott Brooks <21270878+elliette@users.noreply.github.com> Date: Mon, 25 Nov 2024 15:48:20 -0800 Subject: [PATCH 217/386] Click-and-dragging in widget selection mode updates the inspected widget in DevTools (#159352) Fixes https://github.com/flutter/devtools/issues/8539 --- .../lib/src/widgets/widget_inspector.dart | 3 + .../test/widgets/widget_inspector_test.dart | 55 +++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/packages/flutter/lib/src/widgets/widget_inspector.dart b/packages/flutter/lib/src/widgets/widget_inspector.dart index 5e8f9e92d48..6e1bae2f9c2 100644 --- a/packages/flutter/lib/src/widgets/widget_inspector.dart +++ b/packages/flutter/lib/src/widgets/widget_inspector.dart @@ -2958,6 +2958,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); } } diff --git a/packages/flutter/test/widgets/widget_inspector_test.dart b/packages/flutter/test/widgets/widget_inspector_test.dart index 71a15cbdb7f..d1f29781812 100644 --- a/packages/flutter/test/widgets/widget_inspector_test.dart +++ b/packages/flutter/test/widgets/widget_inspector_test.dart @@ -414,6 +414,30 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { ); } + 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, @@ -475,6 +499,37 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { ); 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(); From f3f72ede041883a71cf8c7b6d59fd4ed1455ba28 Mon Sep 17 00:00:00 2001 From: Renzo Olivares Date: Mon, 25 Nov 2024 16:14:30 -0800 Subject: [PATCH 218/386] Add `SelectionListener`/`SelectedContentRange` (#154202) https://github.com/user-attachments/assets/59225cf7-5506-414e-87da-aa4d3227e7f6 Adds: * `SelectionListener`, allows a user to listen to selection changes under the subtree it wraps given their is an ancestor `SelectionArea` or `SelectableRegion`. These selection changes can be listened to through the `SelectionListenerNotifier` that is provided to a `SelectionListener`. * `SelectionListenerNotifier`, used with `SelectionListener`, allows a user listen to selection changes for the subtree of the `SelectionListener` it was provided to. Provides access to individual selection values through the `SelectionDetails` object `selection`. * `SelectableRegionSelectionStatusScope`, allows the user to listen to when a parent `SelectableRegion` is changing or finalizing the selection. * `SelectedContentRange`, provides information about the selection range under a `SelectionHandler` or `Selectable` through the `getSelection()` method. This includes a start and end offset relative to the `Selectable`s content. * `SelectionHandler.contentLength`, to describe the length of the content contained by a selectable. Original PR & Discussion: https://github.com/flutter/flutter/pull/148998 Fixes: #110594 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. --------- Co-authored-by: Renzo Olivares --- .../selectable_region.0.dart | 16 +- .../selection_area/selection_area.1.dart | 136 +++++ .../selection_area/selection_area.2.dart | 407 ++++++++++++++ .../selection_area/selection_area.1_test.dart | 21 + .../selection_area/selection_area.2_test.dart | 125 +++++ .../lib/src/material/selection_area.dart | 2 + .../flutter/lib/src/rendering/paragraph.dart | 17 + .../flutter/lib/src/rendering/selection.dart | 117 +++- ...rm_selectable_region_context_menu_web.dart | 2 +- .../lib/src/widgets/selectable_region.dart | 500 +++++++++++++++++- .../lib/src/widgets/selection_container.dart | 9 + packages/flutter/lib/src/widgets/text.dart | 77 ++- .../selectable_region_context_menu_test.dart | 8 + .../test/widgets/selectable_region_test.dart | 261 +++++++++ 14 files changed, 1664 insertions(+), 34 deletions(-) create mode 100644 examples/api/lib/material/selection_area/selection_area.1.dart create mode 100644 examples/api/lib/material/selection_area/selection_area.2.dart create mode 100644 examples/api/test/material/selection_area/selection_area.1_test.dart create mode 100644 examples/api/test/material/selection_area/selection_area.2_test.dart 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 869d5a01950..7ab61b14617 100644 --- a/examples/api/lib/material/selectable_region/selectable_region.0.dart +++ b/examples/api/lib/material/selectable_region/selectable_region.0.dart @@ -94,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; @@ -272,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/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/packages/flutter/lib/src/material/selection_area.dart b/packages/flutter/lib/src/material/selection_area.dart index 41c949032b5..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]. /// diff --git a/packages/flutter/lib/src/rendering/paragraph.dart b/packages/flutter/lib/src/rendering/paragraph.dart index afe956d96d7..47d4d3e8c2f 100644 --- a/packages/flutter/lib/src/rendering/paragraph.dart +++ b/packages/flutter/lib/src/rendering/paragraph.dart @@ -463,6 +463,9 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin 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/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/selectable_region.dart b/packages/flutter/lib/src/widgets/selectable_region.dart index 430eb316744..a0f2df72df9 100644 --- a/packages/flutter/lib/src/widgets/selectable_region.dart +++ b/packages/flutter/lib/src/widgets/selectable_region.dart @@ -186,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 @@ -208,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. /// @@ -217,10 +241,10 @@ class SelectableRegion extends StatefulWidget { super.key, this.contextMenuBuilder, this.focusNode, - required this.selectionControls, - required this.child, this.magnifierConfiguration = TextMagnifierConfiguration.disabled, this.onSelectionChanged, + required this.selectionControls, + required this.child, }); /// The configuration for the magnifier used with selections in this region. @@ -375,6 +399,9 @@ class SelectableRegionState extends State with TextSelectionDe 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() { @@ -463,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; + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.finalized; } } if (kIsWeb) { @@ -658,9 +687,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) { @@ -671,6 +703,7 @@ class SelectableRegionState extends State with TextSelectionDe break; } _selectWordAt(offset: details.globalPosition); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; if (details.kind != null && !_isPrecisePointerDevice(details.kind!)) { _showHandles(); } @@ -680,6 +713,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) { @@ -690,11 +724,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(); @@ -708,6 +744,7 @@ class SelectableRegionState extends State with TextSelectionDe return; } _selectStartTo(offset: details.globalPosition); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; } _updateSelectedContentIfNeeded(); } @@ -720,6 +757,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: @@ -728,6 +766,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) { @@ -737,6 +776,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(); } @@ -744,6 +784,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) { @@ -754,11 +795,13 @@ 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(); @@ -789,6 +832,7 @@ class SelectableRegionState extends State with TextSelectionDe } _finalizeSelection(); _updateSelectedContentIfNeeded(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.finalized; } void _handleMouseTapUp(TapDragUpDetails details) { @@ -811,11 +855,13 @@ class SelectableRegionState extends State with TextSelectionDe case TargetPlatform.iOS: hideToolbar(); _collapseSelectionAt(offset: details.globalPosition); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.finalized; case TargetPlatform.macOS: case TargetPlatform.linux: case TargetPlatform.windows: // On desktop platforms the selection is set on tap down. - break; + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.finalized; } case 2: final bool isPointerPrecise = _isPrecisePointerDevice(details.kind); @@ -830,6 +876,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. + return; + } // 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(); @@ -841,14 +891,35 @@ class SelectableRegionState extends State with TextSelectionDe // on a double click. break; } + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.finalized; + case 3: + switch (defaultTargetPlatform) { + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.iOS: + if (_isPrecisePointerDevice(details.kind)) { + // Triple tap on static text is only supported on mobile + // platforms using a precise pointer device, so we should + // only update the SelectableRegionSelectionStatus in that case. + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.finalized; + } + case TargetPlatform.macOS: + case TargetPlatform.linux: + case TargetPlatform.windows: + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.finalized; + } } _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); } } @@ -856,6 +927,7 @@ class SelectableRegionState extends State with TextSelectionDe HapticFeedback.selectionClick(); _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. @@ -867,12 +939,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(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.finalized; _showToolbar(); if (defaultTargetPlatform == TargetPlatform.android) { _showHandles(); @@ -902,23 +976,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(); @@ -930,9 +1005,14 @@ class SelectableRegionState extends State with TextSelectionDe if (!lastSecondaryTapDownPositionWasOnActiveSelection) { _collapseSelectionAt(offset: _lastSecondaryTapDownPosition!); } - _showHandles(); - _showToolbar(location: _lastSecondaryTapDownPosition); } + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.finalized; + // Restore _lastSecondaryTapDownPosition since it may be cleared if a user + // accesses contextMenuAnchors. + _lastSecondaryTapDownPosition = details.globalPosition; + _showHandles(); + _showToolbar(location: _lastSecondaryTapDownPosition); _updateSelectedContentIfNeeded(); } @@ -982,9 +1062,9 @@ class SelectableRegionState extends State with TextSelectionDe }, ); } - _stopSelectionStartEdgeUpdate(); - _stopSelectionEndEdgeUpdate(); + _finalizeSelection(); _updateSelectedContentIfNeeded(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.finalized; } void _stopSelectionEndEdgeUpdate() { @@ -1059,6 +1139,7 @@ class SelectableRegionState extends State with TextSelectionDe _selectionDelegate.value.startSelectionPoint!, )); _updateSelectedContentIfNeeded(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; } void _handleSelectionEndHandleDragStart(DragStartDetails details) { @@ -1086,6 +1167,7 @@ class SelectableRegionState extends State with TextSelectionDe _selectionDelegate.value.endSelectionPoint!, )); _updateSelectedContentIfNeeded(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; } MagnifierInfo _buildInfoForMagnifier(Offset globalGesturePosition, SelectionPoint selectionPoint) { @@ -1310,6 +1392,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); } @@ -1410,9 +1494,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( @@ -1456,6 +1544,8 @@ class SelectableRegionState extends State with TextSelectionDe ), ); _updateSelectedContentIfNeeded(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.finalized; } double? _directionalHorizontalBaseline; @@ -1478,6 +1568,8 @@ class SelectableRegionState extends State with TextSelectionDe ), ); _updateSelectedContentIfNeeded(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.finalized; } // [TextSelectionDelegate] overrides. @@ -1509,6 +1601,8 @@ class SelectableRegionState extends State with TextSelectionDe case TargetPlatform.android: case TargetPlatform.fuchsia: clearSelection(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.finalized; case TargetPlatform.iOS: hideToolbar(false); case TargetPlatform.linux: @@ -1538,6 +1632,8 @@ class SelectableRegionState extends State with TextSelectionDe case TargetPlatform.android: case TargetPlatform.fuchsia: clearSelection(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.finalized; case TargetPlatform.iOS: hideToolbar(false); case TargetPlatform.linux: @@ -1638,6 +1734,8 @@ class SelectableRegionState extends State with TextSelectionDe _showHandles(); } _updateSelectedContentIfNeeded(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.finalized; } @Deprecated( @@ -1648,6 +1746,8 @@ class SelectableRegionState extends State with TextSelectionDe void copySelection(SelectionChangedCause cause) { _copy(); clearSelection(); + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing; + _selectionStatusNotifier.value = SelectableRegionSelectionStatus.finalized; } @Deprecated( @@ -1713,6 +1813,7 @@ class SelectableRegionState extends State with TextSelectionDe _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(); @@ -1728,10 +1829,13 @@ class SelectableRegionState extends State with TextSelectionDe @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( @@ -2577,6 +2681,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. // @@ -3005,6 +3179,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]. /// @@ -3016,3 +3194,277 @@ 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) { + _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/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/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 c20112d78bc..ab83e3e2e12 100644 --- a/packages/flutter/test/widgets/selectable_region_test.dart +++ b/packages/flutter/test/widgets/selectable_region_test.dart @@ -4692,6 +4692,251 @@ 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; @@ -5139,6 +5384,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, @@ -5221,6 +5474,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( From 1e824af6bd217beb0cc201394c9832316b6150da Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Mon, 25 Nov 2024 21:55:41 -0500 Subject: [PATCH 219/386] Roll Flutter Engine from fe45a6608651 to fb6439918252 (12 revisions) (#159461) https://github.com/flutter/engine/compare/fe45a6608651...fb6439918252 2024-11-26 chris@bracken.jp iOS: Migrate PlatformViewsController to Objective-C (flutter/engine#56790) 2024-11-26 30870216+gaaclarke@users.noreply.github.com Started caching HandleGLES's hash and made them immutable (flutter/engine#56800) 2024-11-26 98614782+auto-submit[bot]@users.noreply.github.com Reverts "[iOS] Full keyboard access scrolling (#56606)" (flutter/engine#56802) 2024-11-26 skia-flutter-autoroll@skia.org Roll Skia from 12c8bd6ac1d9 to c1c8ff84997c (14 revisions) (flutter/engine#56801) 2024-11-25 jonahwilliams@google.com [Impeller] better handle allocation herustics of Android slide in page transition. (flutter/engine#56762) 2024-11-25 chris@bracken.jp iOS: Eliminate logging of non-zero origin platformviews (flutter/engine#56796) 2024-11-25 30870216+gaaclarke@users.noreply.github.com [impeller] gles: started storing the number of handle deletions to avoid reallocation (flutter/engine#56799) 2024-11-25 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from 9o0fWa2xVhmxV6Mtn... to 50xtjbMWWrqay_7m_... (flutter/engine#56795) 2024-11-25 skia-flutter-autoroll@skia.org Roll Dart SDK from df716eaa6ed2 to 4b49546a1dfa (1 revision) (flutter/engine#56793) 2024-11-25 31859944+LongCatIsLooong@users.noreply.github.com [iOS] Full keyboard access scrolling (flutter/engine#56606) 2024-11-25 jonahwilliams@google.com [android] remove fml_check from surface_texture_external_texture (flutter/engine#56760) 2024-11-25 30870216+gaaclarke@users.noreply.github.com removed unused variable for skia initialization (flutter/engine#56791) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from 9o0fWa2xVhmx to 50xtjbMWWrqa If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index ffd5c010764..305a9606ff6 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -fe45a6608651e249e1b54a6379b593b587934b20 +fb6439918252bd295a043370596842610bcb0afd diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index 3140e03baad..04569ad87fc 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -9o0fWa2xVhmxV6Mtn35w09_VsZcYWYbYelewc3wi2UYC +50xtjbMWWrqay_7m_5IdCODqbAK8pVuCJlvH9mn994cC From e9fe719b31cb8ea210c3f8ed4b379f6f81956bb6 Mon Sep 17 00:00:00 2001 From: "auto-submit[bot]" <98614782+auto-submit[bot]@users.noreply.github.com> Date: Tue, 26 Nov 2024 18:08:26 +0000 Subject: [PATCH 220/386] Reverts "Roll Flutter Engine from fe45a6608651 to fb6439918252 (12 revisions) (#159461)" (#159498) Reverts: flutter/flutter#159461 Initiated by: yjbanov Reason for reverting: engine regression https://github.com/flutter/flutter/issues/159497 Original PR Author: engine-flutter-autoroll Reviewed By: {fluttergithubbot} This change reverts the following previous change: https://github.com/flutter/engine/compare/fe45a6608651...fb6439918252 2024-11-26 chris@bracken.jp iOS: Migrate PlatformViewsController to Objective-C (flutter/engine#56790) 2024-11-26 30870216+gaaclarke@users.noreply.github.com Started caching HandleGLES's hash and made them immutable (flutter/engine#56800) 2024-11-26 98614782+auto-submit[bot]@users.noreply.github.com Reverts "[iOS] Full keyboard access scrolling (#56606)" (flutter/engine#56802) 2024-11-26 skia-flutter-autoroll@skia.org Roll Skia from 12c8bd6ac1d9 to c1c8ff84997c (14 revisions) (flutter/engine#56801) 2024-11-25 jonahwilliams@google.com [Impeller] better handle allocation herustics of Android slide in page transition. (flutter/engine#56762) 2024-11-25 chris@bracken.jp iOS: Eliminate logging of non-zero origin platformviews (flutter/engine#56796) 2024-11-25 30870216+gaaclarke@users.noreply.github.com [impeller] gles: started storing the number of handle deletions to avoid reallocation (flutter/engine#56799) 2024-11-25 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from 9o0fWa2xVhmxV6Mtn... to 50xtjbMWWrqay_7m_... (flutter/engine#56795) 2024-11-25 skia-flutter-autoroll@skia.org Roll Dart SDK from df716eaa6ed2 to 4b49546a1dfa (1 revision) (flutter/engine#56793) 2024-11-25 31859944+LongCatIsLooong@users.noreply.github.com [iOS] Full keyboard access scrolling (flutter/engine#56606) 2024-11-25 jonahwilliams@google.com [android] remove fml_check from surface_texture_external_texture (flutter/engine#56760) 2024-11-25 30870216+gaaclarke@users.noreply.github.com removed unused variable for skia initialization (flutter/engine#56791) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from 9o0fWa2xVhmx to 50xtjbMWWrqa If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC aaclarke@google.com,zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md Co-authored-by: auto-submit[bot] --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 305a9606ff6..ffd5c010764 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -fb6439918252bd295a043370596842610bcb0afd +fe45a6608651e249e1b54a6379b593b587934b20 diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index 04569ad87fc..3140e03baad 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -50xtjbMWWrqay_7m_5IdCODqbAK8pVuCJlvH9mn994cC +9o0fWa2xVhmxV6Mtn35w09_VsZcYWYbYelewc3wi2UYC From fae695ed6198715aa06266cf3589853efb2a96d9 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Tue, 26 Nov 2024 13:40:19 -0500 Subject: [PATCH 221/386] Roll Packages from 46aeb2b29d60 to 8ecf4b010143 (5 revisions) (#159489) https://github.com/flutter/packages/compare/46aeb2b29d60...8ecf4b010143 2024-11-26 stuartmorgan@google.com [file_selector] Update Pigeon version for Linux (flutter/packages#8172) 2024-11-25 737941+loic-sharma@users.noreply.github.com [various] Migrate example apps' AppDelegate.swift (flutter/packages#8155) 2024-11-25 737941+loic-sharma@users.noreply.github.com [various] Update example apps' .gitignore (flutter/packages#8156) 2024-11-25 49699333+dependabot[bot]@users.noreply.github.com [gradle]: Bump androidx.annotation:annotation from 1.9.0 to 1.9.1 in /packages/path_provider/path_provider_android/android (flutter/packages#8170) 2024-11-25 37843020+fransdhinta@users.noreply.github.com [vector_graphics_compiler] fix: handle parsing stroke-width with an invalid value (flutter/packages#8004) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-packages-flutter-autoroll Please CC flutter-ecosystem@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/flutter_packages.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/flutter_packages.version b/bin/internal/flutter_packages.version index 7fa1d4bcd18..44e1586382f 100644 --- a/bin/internal/flutter_packages.version +++ b/bin/internal/flutter_packages.version @@ -1 +1 @@ -46aeb2b29d60d3b0492b716baaeed4c803890078 +8ecf4b010143d331461aa466f371a4f6f7f58d83 From 4ff66988389149cd083c575adeead410037a5864 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Tue, 26 Nov 2024 13:01:20 -0800 Subject: [PATCH 222/386] Report usage of `deferred-components` to analytics. (#159307) Towards https://github.com/flutter/flutter/issues/159212. /cc @jtmcdole --------- Co-authored-by: Andrew Kolos --- .../lib/src/commands/assemble.dart | 8 ++++ .../lib/src/commands/build_appbundle.dart | 7 +++ .../hermetic/assemble_test.dart | 29 +++++++++++++ .../permeable/build_appbundle_test.dart | 43 +++++++++++++++++++ 4 files changed, 87 insertions(+) diff --git a/packages/flutter_tools/lib/src/commands/assemble.dart b/packages/flutter_tools/lib/src/commands/assemble.dart index 1f2de226563..69fc1432a6b 100644 --- a/packages/flutter_tools/lib/src/commands/assemble.dart +++ b/packages/flutter_tools/lib/src/commands/assemble.dart @@ -310,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/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/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/permeable/build_appbundle_test.dart b/packages/flutter_tools/test/commands.shard/permeable/build_appbundle_test.dart index 861d03a6e9b..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 @@ -148,6 +148,49 @@ void main() { 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, + }); }); group('Gradle', () { From 21bea32f6620e0f08e9e16fc31617fd88c20a902 Mon Sep 17 00:00:00 2001 From: Elliott Brooks <21270878+elliette@users.noreply.github.com> Date: Tue, 26 Nov 2024 13:22:23 -0800 Subject: [PATCH 223/386] [Widget Inspector] Fix stack overflow error for Flutter web when requesting a large widget tree (#159454) Fixes https://github.com/flutter/devtools/issues/8553 Context: A Flutter web customer with a large widget tree was getting a stack overflow error when they toggled on "show implementation widgets" in the Flutter DevTools Inspector. This is because building the JSON tree recursively was hitting Chrome's stack limit. This PR creates the JSON tree **iteratively** if the `getRootWidgetTree` service extension is called with `fullDetails = false` (which is what DevTools uses to fetch the widget tree). For all other instances of creating a widget JSON map (for example, when fetching widget properties) the recursive implementation is used. This allows properties provided by subclasses implementing `toJsonMap` to be included in the response. Note: Because with this change `toJsonMap` is only called when `fullDetails = true` and `toJsonMapIterative` is only called when `fullDetails = false`, this PR partially reverts the changes in https://github.com/flutter/flutter/pull/157309. --- .../lib/src/foundation/diagnostics.dart | 243 ++++++++++-------- packages/flutter/lib/src/painting/colors.dart | 13 +- .../flutter/lib/src/widgets/framework.dart | 11 +- .../flutter/lib/src/widgets/icon_data.dart | 13 +- .../lib/src/widgets/widget_inspector.dart | 18 +- .../foundation/diagnostics_json_test.dart | 22 +- .../test/widgets/widget_inspector_test.dart | 4 +- 7 files changed, 170 insertions(+), 154 deletions(-) diff --git a/packages/flutter/lib/src/foundation/diagnostics.dart b/packages/flutter/lib/src/foundation/diagnostics.dart index 5d50c0ef22a..1cdb4c7fd44 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,73 @@ 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, + 'truncated': truncated, + ...delegate.additionalNodeProperties(this, fullDetails: false), + if (includeChildren) 'children': childrenJsonList, + }; + } } /// Debugging message displayed like a property. @@ -1872,17 +1966,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 +2022,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 +2206,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 +2328,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 +2466,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 +2544,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 +2664,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 +2674,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/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/widgets/framework.dart b/packages/flutter/lib/src/widgets/framework.dart index e0d5d9377f4..8867da35038 100644 --- a/packages/flutter/lib/src/widgets/framework.dart +++ b/packages/flutter/lib/src/widgets/framework.dart @@ -5382,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/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/widget_inspector.dart b/packages/flutter/lib/src/widgets/widget_inspector.dart index 6e1bae2f9c2..8d80e50efce 100644 --- a/packages/flutter/lib/src/widgets/widget_inspector.dart +++ b/packages/flutter/lib/src/widgets/widget_inspector.dart @@ -1754,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) { @@ -1824,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] diff --git a/packages/flutter/test/foundation/diagnostics_json_test.dart b/packages/flutter/test/foundation/diagnostics_json_test.dart index 867605d62c6..67a517e3d7e 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), diff --git a/packages/flutter/test/widgets/widget_inspector_test.dart b/packages/flutter/test/widgets/widget_inspector_test.dart index d1f29781812..55a84ecad50 100644 --- a/packages/flutter/test/widgets/widget_inspector_test.dart +++ b/packages/flutter/test/widgets/widget_inspector_test.dart @@ -2177,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 @@ -2571,7 +2571,6 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { ), isTrue, ); - expect( allChildrenSatisfyCondition(rootJson, condition: wasCreatedByLocalProject, @@ -5758,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', From 830ec5a3fb71805b0e20ac6fea91ed109cfa0b5d Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Tue, 26 Nov 2024 16:29:13 -0500 Subject: [PATCH 224/386] Roll Flutter Engine from fe45a6608651 to bd165dc27166 (23 revisions) (#159504) https://github.com/flutter/engine/compare/fe45a6608651...bd165dc27166 2024-11-26 chris@bracken.jp Revert "iOS: Migrate PlatformViewsController to Objective-C (#56790)" (flutter/engine#56817) 2024-11-26 chris@bracken.jp iOS: Rename FlutterPlatformViews_Internal.mm (flutter/engine#56816) 2024-11-26 chris@bracken.jp iOS: Eliminate global in platformviews controller (flutter/engine#56805) 2024-11-26 skia-flutter-autoroll@skia.org Roll Skia from a276978ba7c8 to f149f852c70a (1 revision) (flutter/engine#56812) 2024-11-26 skia-flutter-autoroll@skia.org Roll Skia from d7a267d88fd6 to a276978ba7c8 (1 revision) (flutter/engine#56811) 2024-11-26 skia-flutter-autoroll@skia.org Roll Skia from 8d9d892657a7 to d7a267d88fd6 (1 revision) (flutter/engine#56810) 2024-11-26 skia-flutter-autoroll@skia.org Roll Dart SDK from bdb76c714009 to ca02d403f1a8 (1 revision) (flutter/engine#56809) 2024-11-26 skia-flutter-autoroll@skia.org Roll Skia from b697dd1b03b2 to 8d9d892657a7 (1 revision) (flutter/engine#56808) 2024-11-26 skia-flutter-autoroll@skia.org Roll Skia from c1c8ff84997c to b697dd1b03b2 (1 revision) (flutter/engine#56807) 2024-11-26 chris@bracken.jp iOS: Delete FlutterPlatformViewsController.layerPoolSize (flutter/engine#56806) 2024-11-26 skia-flutter-autoroll@skia.org Roll Dart SDK from 4b49546a1dfa to bdb76c714009 (1 revision) (flutter/engine#56803) 2024-11-26 chris@bracken.jp iOS: Migrate PlatformViewsController to Objective-C (flutter/engine#56790) 2024-11-26 30870216+gaaclarke@users.noreply.github.com Started caching HandleGLES's hash and made them immutable (flutter/engine#56800) 2024-11-26 98614782+auto-submit[bot]@users.noreply.github.com Reverts "[iOS] Full keyboard access scrolling (#56606)" (flutter/engine#56802) 2024-11-26 skia-flutter-autoroll@skia.org Roll Skia from 12c8bd6ac1d9 to c1c8ff84997c (14 revisions) (flutter/engine#56801) 2024-11-25 jonahwilliams@google.com [Impeller] better handle allocation herustics of Android slide in page transition. (flutter/engine#56762) 2024-11-25 chris@bracken.jp iOS: Eliminate logging of non-zero origin platformviews (flutter/engine#56796) 2024-11-25 30870216+gaaclarke@users.noreply.github.com [impeller] gles: started storing the number of handle deletions to avoid reallocation (flutter/engine#56799) 2024-11-25 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from 9o0fWa2xVhmxV6Mtn... to 50xtjbMWWrqay_7m_... (flutter/engine#56795) 2024-11-25 skia-flutter-autoroll@skia.org Roll Dart SDK from df716eaa6ed2 to 4b49546a1dfa (1 revision) (flutter/engine#56793) 2024-11-25 31859944+LongCatIsLooong@users.noreply.github.com [iOS] Full keyboard access scrolling (flutter/engine#56606) 2024-11-25 jonahwilliams@google.com [android] remove fml_check from surface_texture_external_texture (flutter/engine#56760) 2024-11-25 30870216+gaaclarke@users.noreply.github.com removed unused variable for skia initialization (flutter/engine#56791) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from 9o0fWa2xVhmx to 50xtjbMWWrqa If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index ffd5c010764..4c744c5f3d9 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -fe45a6608651e249e1b54a6379b593b587934b20 +bd165dc27166c7d2cb58de70f3f1938e8810d08e diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index 3140e03baad..04569ad87fc 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -9o0fWa2xVhmxV6Mtn35w09_VsZcYWYbYelewc3wi2UYC +50xtjbMWWrqay_7m_5IdCODqbAK8pVuCJlvH9mn994cC From 4a4d7a7dac8aab7c3b27d44352d994cfea7b2925 Mon Sep 17 00:00:00 2001 From: Mitchell Goodwin <58190796+MitchellGoodwin@users.noreply.github.com> Date: Tue, 26 Nov 2024 15:59:14 -0800 Subject: [PATCH 225/386] Suppress previous route transition if current route is fullscreenDialog (#159312) Fixes #159289 Cupertino and Material routes were looking to see if the next route was a full screen dialog route, and not transitioning accordingly. However with the updates to allow [mixed transitions in an app](https://github.com/flutter/flutter/pull/150031), any route will try and transition if a delegatedTransition is available. This PR makes it so that Cupertino and Material routes that are fullscreen dialogs will use `canTransitionFrom` to tell the previous route not to transition. Before: [388677067-d301238d-6615-42a7-b60a-611c61136d88.webm](https://github.com/user-attachments/assets/eea99ee9-0bc8-4981-a950-08f99a7fdb3e) After: https://github.com/user-attachments/assets/7deb5143-cd67-4696-95ec-9d7df329dfa4 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [ ] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- packages/flutter/lib/src/cupertino/route.dart | 6 +++ packages/flutter/lib/src/material/page.dart | 6 +++ .../flutter/test/cupertino/route_test.dart | 48 +++++++++++++++++++ packages/flutter/test/material/page_test.dart | 48 +++++++++++++++++++ 4 files changed, 108 insertions(+) diff --git a/packages/flutter/lib/src/cupertino/route.dart b/packages/flutter/lib/src/cupertino/route.dart index 390bac8b41e..ae68440c214 100644 --- a/packages/flutter/lib/src/cupertino/route.dart +++ b/packages/flutter/lib/src/cupertino/route.dart @@ -175,6 +175,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); diff --git a/packages/flutter/lib/src/material/page.dart b/packages/flutter/lib/src/material/page.dart index 2b87aaa9783..5a5fe8122b9 100644 --- a/packages/flutter/lib/src/material/page.dart +++ b/packages/flutter/lib/src/material/page.dart @@ -124,6 +124,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/test/cupertino/route_test.dart b/packages/flutter/test/cupertino/route_test.dart index 182bf0b70d5..fa715288067 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(); 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( From a4a4e57bc62b87c894a870c11dc0fcc5827c6405 Mon Sep 17 00:00:00 2001 From: davidhicks980 <59215665+davidhicks980@users.noreply.github.com> Date: Tue, 26 Nov 2024 20:42:37 -0500 Subject: [PATCH 226/386] Reland CupertinoPopupSurface (#159272) https://github.com/flutter/flutter/pull/151430 had to be reverted because of a black square appearing during animations. This PR fixes the issue by switching from BlendMode.src -> BlendMode.srcOver. I visually checked to make sure the issue was fixed on MacOS and iOS/Android simulators. Fixes https://github.com/flutter/flutter/issues/154887 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --------- Co-authored-by: Tong Mu --- .../flutter/lib/src/cupertino/dialog.dart | 198 ++++++++- .../test/cupertino/popup_surface_test.dart | 384 ++++++++++++++++++ 2 files changed, 561 insertions(+), 21 deletions(-) create mode 100644 packages/flutter/test/cupertino/popup_surface_test.dart diff --git a/packages/flutter/lib/src/cupertino/dialog.dart b/packages/flutter/lib/src/cupertino/dialog.dart index c264683d081..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; @@ -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, 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'), + ); + }); +} From 28fde86b7c255f62d58ef5eee9953d8aa610d400 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Tue, 26 Nov 2024 22:00:25 -0500 Subject: [PATCH 227/386] Roll Flutter Engine from bd165dc27166 to da71729651d8 (7 revisions) (#159523) https://github.com/flutter/engine/compare/bd165dc27166...da71729651d8 2024-11-27 skia-flutter-autoroll@skia.org Roll Dart SDK from 72b594775c83 to 0740ded7b9bf (1 revision) (flutter/engine#56826) 2024-11-27 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from 50xtjbMWWrqay_7m_... to u0agumUB4Ag6cTiKk... (flutter/engine#56823) 2024-11-27 flar@google.com [DisplayList] Delete (publicly) unused DlColorColorSource (flutter/engine#56825) 2024-11-26 jonahwilliams@google.com [engine] reland: more consistently flush message loops tasks (flutter/engine#56815) 2024-11-26 jonahwilliams@google.com [Impeller] cache even more text frame data to skip lookups. (flutter/engine#56798) 2024-11-26 flar@google.com [DisplayList] migrate DlColorFilter objects to new source layout (flutter/engine#56785) 2024-11-26 skia-flutter-autoroll@skia.org Roll Dart SDK from ca02d403f1a8 to 72b594775c83 (1 revision) (flutter/engine#56819) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from 50xtjbMWWrqa to u0agumUB4Ag6 If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 4c744c5f3d9..17fd6061a82 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -bd165dc27166c7d2cb58de70f3f1938e8810d08e +da71729651d8f641cb2ea21df6286afd75f1bd1e diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index 04569ad87fc..a481bc3034e 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -50xtjbMWWrqay_7m_5IdCODqbAK8pVuCJlvH9mn994cC +u0agumUB4Ag6cTiKkU_LX30L_hjFI5-jFlHnArgyehwC From 3a328e7d633d27824a9eed4e3949989c77cf7821 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Wed, 27 Nov 2024 00:51:30 -0500 Subject: [PATCH 228/386] Roll Flutter Engine from da71729651d8 to b9474a99694c (2 revisions) (#159527) https://github.com/flutter/engine/compare/da71729651d8...b9474a99694c 2024-11-27 chris@bracken.jp Reland: iOS: Migrate PlatformViewsController to Objective-C (flutter/engine#56828) 2024-11-27 jonahwilliams@google.com [Impeller] make sampler use string_view instead of std::string. (flutter/engine#56821) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 17fd6061a82..a2350d0832b 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -da71729651d8f641cb2ea21df6286afd75f1bd1e +b9474a99694c70d472fd8d3acc0c55b5271ce9e1 From c6260a86f662c72c13cb3ee26ffad89642afd32b Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Wed, 27 Nov 2024 03:21:37 -0500 Subject: [PATCH 229/386] Roll Flutter Engine from b9474a99694c to 4121287c360a (1 revision) (#159530) https://github.com/flutter/engine/compare/b9474a99694c...4121287c360a 2024-11-27 chris@bracken.jp Reland: iOS: Delete FlutterPlatformViewsController.layerPoolSize (flutter/engine#56830) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index a2350d0832b..b588c707cc9 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -b9474a99694c70d472fd8d3acc0c55b5271ce9e1 +4121287c360a096d2ba3161be66021bfe0c4f8b6 From 4aa2caef20a9d4c930a53ad04f0791e907b63815 Mon Sep 17 00:00:00 2001 From: Daco Harkes Date: Wed, 27 Nov 2024 12:03:19 +0100 Subject: [PATCH 230/386] [native assets] Create `NativeAssetsManifest.json` instead of kernel embedding (#159322) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This PR introduces a `NativeAssetsManifest.json` next to the `AssetManifest.bin` and `FontManifest.json`. This removes the need for embedding the native assets mapping inside the kernel file and enables decoupling native assets building and bundling from the kernel compilation in flutter tools. This means `flutter run` no longer does a dry run of `hook/build.dart` hooks. (It also means all isolate groups will have the same native assets. However, since Flutter does not support `Isolate.spawnUri` from kernel files, this is not a regression.) Implementation details: * g3 is still using kernel embedding. https://github.com/flutter/flutter/pull/142016 introduced an argument to embed a `native_assets.yaml` inside `flutter attach` and `flutter run` (the outer flutter process), but it is not used in `flutter assemble` (the inner process when doing `flutter run`). So, those arguments need to still be respected. However, all other logic related to embedding a yaml encoding in the kernel file has been removed. * All dry-run logic has been removed. 🎉 * The `KernelSnapshot` target no longer depends on the `InstallCodeAssets` target. Instead, the various OS-specific "BundleAsset" targets now depend on the `InstallCodeAssets` target. The `InstallCodeAssets` invokes the build hooks and produces the `NativeAssetsManifest.json`. The various "BundleAsset" commands synchronize the `NativeAssetsManifest.json` to the app bundle. * `InstallCodeAssets` produces a `native_assets.json`, which is renamed to `NativeAssetsManifest.json` in the various "Bundle" targets. This means that all unit tests of the "Bundle" targets now need to create this file. (Similar to how `app.dill` is expected to exist because `KernelSnapshot` is a dependency of the "Bundle" targets.) * Because dynamic libraries need to be code signed (at least on iOS and MacOS), the bundling of the dylibs is _not_ migrated to reuse `_updateDevFS` (which is used for ordinary assets). Only the 2nd and 3rd invocation of `flutter assemble` from `xcodebuild` has access to the code signing identity. Relevant tests: * test/integration.shard/isolated/native_assets_test.dart - runs `flutter run` with native assets including hot restart and hot reload. TODO: * Undo engine-roll in this PR after engine has rolled in. Issue: * https://github.com/flutter/flutter/issues/154425 Related PRs: * https://dart-review.googlesource.com/c/sdk/+/388161 * https://github.com/flutter/engine/pull/56727 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- packages/flutter_tools/bin/macos_assemble.sh | 2 +- packages/flutter_tools/bin/xcode_backend.dart | 2 + packages/flutter_tools/lib/executable.dart | 3 - .../lib/src/build_system/targets/android.dart | 7 + .../lib/src/build_system/targets/assets.dart | 6 + .../lib/src/build_system/targets/common.dart | 163 +----------- .../lib/src/build_system/targets/ios.dart | 9 + .../lib/src/build_system/targets/linux.dart | 4 + .../lib/src/build_system/targets/macos.dart | 9 + .../build_system/targets/native_assets.dart | 9 +- .../lib/src/build_system/targets/windows.dart | 7 + .../lib/src/commands/attach.dart | 11 +- .../lib/src/commands/build_ios_framework.dart | 2 + .../src/commands/build_macos_framework.dart | 2 + .../lib/src/commands/daemon.dart | 2 - .../flutter_tools/lib/src/commands/run.dart | 8 +- .../flutter_tools/lib/src/commands/test.dart | 22 +- .../isolated/native_assets/native_assets.dart | 239 +++--------------- .../native_assets/test/native_assets.dart | 4 +- packages/flutter_tools/lib/src/run_hot.dart | 33 +-- .../lib/src/test/flutter_platform.dart | 2 - .../flutter_tools/lib/src/test/runner.dart | 4 - .../lib/src/test/test_compiler.dart | 10 +- .../commands.shard/hermetic/attach_test.dart | 1 - .../commands.shard/hermetic/run_test.dart | 2 - .../build_system/targets/android_test.dart | 7 + .../build_system/targets/assets_test.dart | 1 + .../build_system/targets/common_test.dart | 165 +++--------- .../build_system/targets/ios_test.dart | 4 + .../build_system/targets/linux_test.dart | 3 + .../build_system/targets/macos_test.dart | 13 + .../build_system/targets/windows_test.dart | 3 + .../isolated/android/native_assets_test.dart | 2 +- .../targets/native_assets_test.dart | 2 +- .../fake_native_assets_build_runner.dart | 50 +--- .../test/general.shard/isolated/hot_test.dart | 182 ------------- .../isolated/native_assets_test.dart | 140 +--------- .../isolated/resident_runner_test.dart | 11 +- .../isolated/windows/native_assets_test.dart | 5 +- 39 files changed, 197 insertions(+), 954 deletions(-) delete mode 100644 packages/flutter_tools/test/general.shard/isolated/hot_test.dart 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/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/lib/executable.dart b/packages/flutter_tools/lib/executable.dart index 1ebf5c1ee82..1d67a73e4e6 100644 --- a/packages/flutter_tools/lib/executable.dart +++ b/packages/flutter_tools/lib/executable.dart @@ -49,7 +49,6 @@ 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 +180,6 @@ List generateCommands({ platform: globals.platform, processInfo: globals.processInfo, fileSystem: globals.fs, - nativeAssetsBuilder: const HotRunnerNativeAssetsBuilderImpl(), ), BuildCommand( artifacts: globals.artifacts!, @@ -244,7 +242,6 @@ List generateCommands({ ), RunCommand( verboseHelp: verboseHelp, - nativeAssetsBuilder: const HotRunnerNativeAssetsBuilderImpl(), ), ScreenshotCommand(fs: globals.fs), ShellCompletionCommand(), 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 d9c4243eac0..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}/${InstallCodeAssets.nativeAssetsFilename}'), - ...const KernelSnapshotProgram().inputs, - ]; - - @override - List get outputs => const [ - Source.pattern('{BUILD_DIR}/${KernelSnapshotNativeAssets.dillName}'), - ]; - - @override - List get depfiles => const []; - - @override - List get dependencies => const [ - InstallCodeAssets(), - ]; - - static const String dillName = 'native_assets.dill'; - - @override - Future build(Environment environment) async { - final File nativeAssetsFile = environment.buildDir.childFile(InstallCodeAssets.nativeAssetsFilename); - 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/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 af1a80615d8..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 @@ -116,7 +116,7 @@ class DartBuildForNative extends DartBuild { @override List get dependencies => const [ - KernelSnapshotProgram(), + KernelSnapshot(), ]; } @@ -125,11 +125,6 @@ class DartBuildForNative extends DartBuild { /// 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. class InstallCodeAssets extends Target { const InstallCodeAssets(); @@ -188,7 +183,7 @@ class InstallCodeAssets extends Target { Source.pattern('{BUILD_DIR}/$nativeAssetsFilename'), ]; - static const String nativeAssetsFilename = 'native_assets.yaml'; + static const String nativeAssetsFilename = 'native_assets.json'; static const String depFilename = 'install_code_assets.d'; } 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/commands/attach.dart b/packages/flutter_tools/lib/src/commands/attach.dart index c5b4dd6501e..7945925fdd0 100644 --- a/packages/flutter_tools/lib/src/commands/attach.dart +++ b/packages/flutter_tools/lib/src/commands/attach.dart @@ -68,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, @@ -76,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); @@ -149,7 +147,6 @@ class AttachCommand extends FlutterCommand { final Platform _platform; final ProcessInfo _processInfo; final FileSystem _fileSystem; - final HotRunnerNativeAssetsBuilder? _nativeAssetsBuilder; @override final String name = 'attach'; @@ -348,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 { @@ -381,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; @@ -438,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(); @@ -475,7 +469,6 @@ 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, ) : ColdRunner( @@ -507,7 +500,6 @@ class HotRunnerFactory { bool stayResident = true, FlutterProject? flutterProject, String? nativeAssetsYamlFile, - required HotRunnerNativeAssetsBuilder? nativeAssetsBuilder, required Analytics analytics, }) => HotRunner( devices, @@ -520,7 +512,6 @@ class HotRunnerFactory { dillOutputPath: dillOutputPath, stayResident: stayResident, nativeAssetsYamlFile: nativeAssetsYamlFile, - nativeAssetsBuilder: nativeAssetsBuilder, analytics: analytics, ); } 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 fc424ca9e12..795f89bd3c0 100644 --- a/packages/flutter_tools/lib/src/commands/build_ios_framework.dart +++ b/packages/flutter_tools/lib/src/commands/build_ios_framework.dart @@ -286,6 +286,8 @@ class BuildIOSFrameworkCommand extends BuildFrameworkCommand { '- .DS_Store', '--filter', '- native_assets.yaml', + '--filter', + '- native_assets.json', nativeAssetsDirectory.path, modeDirectory.path, ]); 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 7794b72860b..f99158891be 100644 --- a/packages/flutter_tools/lib/src/commands/build_macos_framework.dart +++ b/packages/flutter_tools/lib/src/commands/build_macos_framework.dart @@ -118,6 +118,8 @@ class BuildMacOSFrameworkCommand extends BuildFrameworkCommand { '- .DS_Store', '--filter', '- native_assets.yaml', + '--filter', + '- native_assets.json', nativeAssetsDirectory.path, modeDirectory.path, ]); diff --git a/packages/flutter_tools/lib/src/commands/daemon.dart b/packages/flutter_tools/lib/src/commands/daemon.dart index 98e81cf1c41..3e90e59ac5a 100644 --- a/packages/flutter_tools/lib/src/commands/daemon.dart +++ b/packages/flutter_tools/lib/src/commands/daemon.dart @@ -667,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 +716,6 @@ class AppDomain extends Domain { hostIsIde: true, machine: machine, analytics: globals.analytics, - nativeAssetsBuilder: nativeAssetsBuilder, ); } else { runner = ColdRunner( diff --git a/packages/flutter_tools/lib/src/commands/run.dart b/packages/flutter_tools/lib/src/commands/run.dart index f2e6d16474f..03e607f26af 100644 --- a/packages/flutter_tools/lib/src/commands/run.dart +++ b/packages/flutter_tools/lib/src/commands/run.dart @@ -349,9 +349,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); @@ -435,8 +433,6 @@ class RunCommand extends RunCommandBase { ); } - final HotRunnerNativeAssetsBuilder? _nativeAssetsBuilder; - @override final String name = 'run'; @@ -695,7 +691,6 @@ class RunCommand extends RunCommandBase { stayResident: stayResident, analytics: globals.analytics, nativeAssetsYamlFile: stringArg(FlutterOptions.kNativeAssetsYamlFile), - nativeAssetsBuilder: _nativeAssetsBuilder, ); } else if (webMode) { return webRunnerFactory!.createWebRunner( @@ -765,7 +760,6 @@ 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()); diff --git a/packages/flutter_tools/lib/src/commands/test.dart b/packages/flutter_tools/lib/src/commands/test.dart index 0183f843bbf..fd779f5c055 100644 --- a/packages/flutter_tools/lib/src/commands/test.dart +++ b/packages/flutter_tools/lib/src/commands/test.dart @@ -419,7 +419,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 +428,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 +597,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 +624,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/isolated/native_assets/native_assets.dart b/packages/flutter_tools/lib/src/isolated/native_assets/native_assets.dart index 686e0007dbf..999e7e0dd45 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'; @@ -129,67 +128,7 @@ Future installCodeAssets({ 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); - final KernelAssets kernelAssets = KernelAssets(assetTargetLocations.values.toList()); - await _writeNativeAssetsYaml(kernelAssets, nativeAssetsFileUri, fileSystem); -} - -Future runFlutterSpecificDartDryRunOnPlatforms({ - required Uri projectUri, - required FileSystem fileSystem, - required FlutterNativeAssetsBuildRunner buildRunner, - required List targetPlatforms, -}) async { - if (!await _nativeBuildRequired(buildRunner)) { - return null; - } - - 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; + await _writeNativeAssetsJson(assetTargetLocations.values.toList(), nativeAssetsFileUri, fileSystem,); } /// Programmatic API to be used by Dart launchers to invoke native builds. @@ -199,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, @@ -307,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, @@ -418,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); @@ -435,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) { @@ -518,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, @@ -830,44 +710,6 @@ Future _runDartBuild({ 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 _architecturesForOS(build_info.TargetPlatform targetPlatform, OS targetOS, Map environmentDefines) { switch (targetOS) { @@ -953,12 +795,6 @@ Future _copyNativeCodeAssetsToBundleOnWindowsLinux( } } -Never _throwNativeAssetsBuildDryRunFailed() { - throwToolExit( - 'Building (dry run) native assets failed. See the logs for more details.', - ); -} - Never _throwNativeAssetsBuildFailed() { throwToolExit( 'Building native assets failed. See the logs for more details.', @@ -1049,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]!; } 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 679053f0d8c..431369ed1ea 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 @@ -52,11 +52,11 @@ Future testCompilerBuildNativeAssets(BuildInfo buildInfo) async { } // Only `flutter test` uses the - // `build/native_assets//native_assets.yaml` file which uses absolute + // `build/native_assets//native_assets.json` file which uses absolute // paths to the shared libraries. final OS targetOS = getNativeOSFromTargetPlatfrorm(TargetPlatform.tester); final Uri buildUri = nativeAssetsBuildUri(projectUri, targetOS); - final Uri nativeAssetsFileUri = buildUri.resolve('native_assets.yaml'); + final Uri nativeAssetsFileUri = buildUri.resolve('native_assets.json'); final Map environmentDefines = { kBuildMode: buildInfo.mode.cliName, diff --git a/packages/flutter_tools/lib/src/run_hot.dart b/packages/flutter_tools/lib/src/run_hot.dart index fcdf085b899..0b7e525de00 100644 --- a/packages/flutter_tools/lib/src/run_hot.dart +++ b/packages/flutter_tools/lib/src/run_hot.dart @@ -90,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( @@ -131,7 +129,6 @@ class HotRunner extends ResidentRunner { String? _sdkName; bool? _emulator; - final HotRunnerNativeAssetsBuilder? _nativeAssetsBuilder; final String? _nativeAssetsYamlFile; String? flavor; @@ -378,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); @@ -1708,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/test/flutter_platform.dart b/packages/flutter_tools/lib/src/test/flutter_platform.dart index 9e85534b1d4..8ba1919d490 100644 --- a/packages/flutter_tools/lib/src/test/flutter_platform.dart +++ b/packages/flutter_tools/lib/src/test/flutter_platform.dart @@ -529,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. @@ -556,7 +555,6 @@ class FlutterPlatform extends PlatformPlugin { debuggingOptions.buildInfo, flutterProject, testTimeRecorder: testTimeRecorder, - nativeAssetsBuilder: nativeAssetsBuilder, ); mainDart = await compiler!.compile(globals.fs.file(mainDart).uri); 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/test/commands.shard/hermetic/attach_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/attach_test.dart index 31ce4464493..00cfd4f1f6b 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/attach_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/attach_test.dart @@ -1258,7 +1258,6 @@ class FakeHotRunnerFactory extends Fake implements HotRunnerFactory { FlutterProject? flutterProject, Analytics? analytics, String? nativeAssetsYamlFile, - HotRunnerNativeAssetsBuilder? nativeAssetsBuilder, }) { if (_artifactTester != null) { for (final FlutterDevice device in devices) { 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 1474fe995d9..e43dd417b86 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/run_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/run_test.dart @@ -27,7 +27,6 @@ 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/web/compile.dart'; import 'package:test/fake.dart'; @@ -1611,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/general.shard/build_system/targets/android_test.dart b/packages/flutter_tools/test/general.shard/build_system/targets/android_test.dart index 9678defbba5..d0c2c696d1f 100644 --- a/packages/flutter_tools/test/general.shard/build_system/targets/android_test.dart +++ b/packages/flutter_tools/test/general.shard/build_system/targets/android_test.dart @@ -52,6 +52,7 @@ void main() { // create pre-requisites. environment.buildDir.childFile('app.dill') .writeAsStringSync('abcd'); + environment.buildDir.childFile('native_assets.json').createSync(); fileSystem .file(artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug)) .createSync(recursive: true); @@ -96,6 +97,7 @@ void main() { // create pre-requisites. environment.buildDir.childFile('app.dill') .writeAsStringSync('abcd'); + environment.buildDir.childFile('native_assets.json').createSync(); fileSystem .file(artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug)) .createSync(recursive: true); @@ -185,6 +187,7 @@ void main() { )); environment.buildDir.createSync(recursive: true); environment.buildDir.childFile('app.dill').createSync(); + environment.buildDir.childFile('native_assets.json').createSync(); const AndroidAot androidAot = AndroidAot(TargetPlatform.android_arm64, BuildMode.release); await androidAot.build(environment); @@ -223,6 +226,7 @@ void main() { )); environment.buildDir.createSync(recursive: true); environment.buildDir.childFile('app.dill').createSync(); + environment.buildDir.childFile('native_assets.json').createSync(); const AndroidAot androidAot = AndroidAot(TargetPlatform.android_arm64, BuildMode.release); await androidAot.build(environment); @@ -264,6 +268,7 @@ void main() { )); environment.buildDir.createSync(recursive: true); environment.buildDir.childFile('app.dill').createSync(); + environment.buildDir.childFile('native_assets.json').createSync(); await const AndroidAot(TargetPlatform.android_arm64, BuildMode.release) .build(environment); @@ -301,6 +306,7 @@ void main() { )); environment.buildDir.createSync(recursive: true); environment.buildDir.childFile('app.dill').createSync(); + environment.buildDir.childFile('native_assets.json').createSync(); await const AndroidAot(TargetPlatform.android_arm64, BuildMode.release) .build(environment); @@ -518,6 +524,7 @@ void main() { // create pre-requisites. environment.buildDir.childFile('app.dill') .writeAsStringSync('abcd'); + environment.buildDir.childFile('native_assets.json').createSync(); fileSystem .file(artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug)) .createSync(recursive: true); diff --git a/packages/flutter_tools/test/general.shard/build_system/targets/assets_test.dart b/packages/flutter_tools/test/general.shard/build_system/targets/assets_test.dart index 5270de45078..fc768cf3b60 100644 --- a/packages/flutter_tools/test/general.shard/build_system/targets/assets_test.dart +++ b/packages/flutter_tools/test/general.shard/build_system/targets/assets_test.dart @@ -43,6 +43,7 @@ void main() { }, ); fileSystem.file(environment.buildDir.childFile('app.dill')).createSync(recursive: true); + fileSystem.file(environment.buildDir.childFile('native_assets.json')).createSync(recursive: true); fileSystem.file('packages/flutter_tools/lib/src/build_system/targets/assets.dart') .createSync(recursive: true); fileSystem.file('assets/foo/bar.png') diff --git a/packages/flutter_tools/test/general.shard/build_system/targets/common_test.dart b/packages/flutter_tools/test/general.shard/build_system/targets/common_test.dart index 40032cc3337..88b7272822d 100644 --- a/packages/flutter_tools/test/general.shard/build_system/targets/common_test.dart +++ b/packages/flutter_tools/test/general.shard/build_system/targets/common_test.dart @@ -12,7 +12,6 @@ import 'package:flutter_tools/src/build_system/build_system.dart'; import 'package:flutter_tools/src/build_system/exceptions.dart'; import 'package:flutter_tools/src/build_system/targets/common.dart'; import 'package:flutter_tools/src/build_system/targets/ios.dart'; -import 'package:flutter_tools/src/build_system/targets/native_assets.dart'; import 'package:flutter_tools/src/compile.dart'; import '../../../src/common.dart'; @@ -65,34 +64,14 @@ void main() { iosEnvironment.buildDir.createSync(recursive: true); }); - testWithoutContext('KernelSnapshotProgram throws error if missing build mode', () async { + testWithoutContext('KernelSnapshot throws error if missing build mode', () async { androidEnvironment.defines.remove(kBuildMode); expect( - const KernelSnapshotProgram().build(androidEnvironment), + const KernelSnapshot().build(androidEnvironment), throwsA(isA())); }); - const String emptyNativeAssets = ''' -format-version: - - 1 - - 0 - - 0 -native-assets: {} -'''; - - const String nonEmptyNativeAssets = ''' -format-version: - - 1 - - 0 - - 0 -native-assets: - macos_arm64: - package:my_package/my_package_bindings_generated.dart: - - absolute - - my_package.framework/my_package -'''; - - testWithoutContext('KernelSnapshotProgram handles null result from kernel compilation', () async { + testWithoutContext('KernelSnapshot handles null result from kernel compilation', () async { fileSystem.file('.dart_tool/package_config.json') ..createSync(recursive: true) ..writeAsStringSync('{"configVersion": 2, "packages":[]}'); @@ -119,7 +98,7 @@ native-assets: '--packages', '/.dart_tool/package_config.json', '--output-dill', - '$build/program.dill', + '$build/app.dill', '--depfile', '$build/kernel_snapshot_program.d', '--verbosity=error', @@ -127,11 +106,11 @@ native-assets: ], exitCode: 1), ]); - await expectLater(() => const KernelSnapshotProgram().build(androidEnvironment), throwsException); + await expectLater(() => const KernelSnapshot().build(androidEnvironment), throwsException); expect(processManager, hasNoRemainingExpectations); }); - testWithoutContext('KernelSnapshotProgram does use track widget creation on profile builds', () async { + testWithoutContext('KernelSnapshot does use track widget creation on profile builds', () async { fileSystem.file('.dart_tool/package_config.json') ..createSync(recursive: true) ..writeAsStringSync('{"configVersion": 2, "packages":[]}'); @@ -158,20 +137,20 @@ native-assets: '--packages', '/.dart_tool/package_config.json', '--output-dill', - '$build/program.dill', + '$build/app.dill', '--depfile', '$build/kernel_snapshot_program.d', '--verbosity=error', 'file:///lib/main.dart', - ], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/program.dill 0\n'), + ], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'), ]); - await const KernelSnapshotProgram().build(androidEnvironment); + await const KernelSnapshot().build(androidEnvironment); expect(processManager, hasNoRemainingExpectations); }); - testWithoutContext('KernelSnapshotProgram correctly handles an empty string in ExtraFrontEndOptions', () async { + testWithoutContext('KernelSnapshot correctly handles an empty string in ExtraFrontEndOptions', () async { fileSystem.file('.dart_tool/package_config.json') ..createSync(recursive: true) ..writeAsStringSync('{"configVersion": 2, "packages":[]}'); @@ -198,21 +177,21 @@ native-assets: '--packages', '/.dart_tool/package_config.json', '--output-dill', - '$build/program.dill', + '$build/app.dill', '--depfile', '$build/kernel_snapshot_program.d', '--verbosity=error', 'file:///lib/main.dart', - ], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/program.dill 0\n'), + ], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'), ]); - await const KernelSnapshotProgram() + await const KernelSnapshot() .build(androidEnvironment..defines[kExtraFrontEndOptions] = ''); expect(processManager, hasNoRemainingExpectations); }); - testWithoutContext('KernelSnapshotProgram correctly forwards FrontendServerStarterPath', () async { + testWithoutContext('KernelSnapshot correctly forwards FrontendServerStarterPath', () async { fileSystem.file('.dart_tool/package_config.json') ..createSync(recursive: true) ..writeAsStringSync('{"configVersion": 2, "packages":[]}'); @@ -239,21 +218,21 @@ native-assets: '--packages', '/.dart_tool/package_config.json', '--output-dill', - '$build/program.dill', + '$build/app.dill', '--depfile', '$build/kernel_snapshot_program.d', '--verbosity=error', 'file:///lib/main.dart', - ], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/program.dill 0\n'), + ], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'), ]); - await const KernelSnapshotProgram() + await const KernelSnapshot() .build(androidEnvironment..defines[kFrontendServerStarterPath] = 'path/to/frontend_server_starter.dart'); expect(processManager, hasNoRemainingExpectations); }); - testWithoutContext('KernelSnapshotProgram correctly forwards ExtraFrontEndOptions', () async { + testWithoutContext('KernelSnapshot correctly forwards ExtraFrontEndOptions', () async { fileSystem.file('.dart_tool/package_config.json') ..createSync(recursive: true) ..writeAsStringSync('{"configVersion": 2, "packages":[]}'); @@ -280,23 +259,23 @@ native-assets: '--packages', '/.dart_tool/package_config.json', '--output-dill', - '$build/program.dill', + '$build/app.dill', '--depfile', '$build/kernel_snapshot_program.d', '--verbosity=error', 'foo', 'bar', 'file:///lib/main.dart', - ], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/program.dill 0\n'), + ], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'), ]); - await const KernelSnapshotProgram() + await const KernelSnapshot() .build(androidEnvironment..defines[kExtraFrontEndOptions] = 'foo,bar'); expect(processManager, hasNoRemainingExpectations); }); - testWithoutContext('KernelSnapshotProgram can disable track-widget-creation on debug builds', () async { + testWithoutContext('KernelSnapshot can disable track-widget-creation on debug builds', () async { fileSystem.file('.dart_tool/package_config.json') ..createSync(recursive: true) ..writeAsStringSync('{"configVersion": 2, "packages":[]}'); @@ -320,25 +299,25 @@ native-assets: '--packages', '/.dart_tool/package_config.json', '--output-dill', - '$build/program.dill', + '$build/app.dill', '--depfile', '$build/kernel_snapshot_program.d', '--incremental', '--initialize-from-dill', - '$build/program.dill', + '$build/app.dill', '--verbosity=error', 'file:///lib/main.dart', - ], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/program.dill 0\n'), + ], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'), ]); - await const KernelSnapshotProgram().build(androidEnvironment + await const KernelSnapshot().build(androidEnvironment ..defines[kBuildMode] = BuildMode.debug.cliName ..defines[kTrackWidgetCreation] = 'false'); expect(processManager, hasNoRemainingExpectations); }); - testWithoutContext('KernelSnapshotProgram forces platform linking on debug for darwin target platforms', () async { + testWithoutContext('KernelSnapshot forces platform linking on debug for darwin target platforms', () async { fileSystem.file('.dart_tool/package_config.json') ..createSync(recursive: true) ..writeAsStringSync('{"configVersion": 2, "packages":[]}'); @@ -360,18 +339,18 @@ native-assets: '--packages', '/.dart_tool/package_config.json', '--output-dill', - '$build/program.dill', + '$build/app.dill', '--depfile', '$build/kernel_snapshot_program.d', '--incremental', '--initialize-from-dill', - '$build/program.dill', + '$build/app.dill', '--verbosity=error', 'file:///lib/main.dart', - ], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/program.dill 0\n'), + ], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'), ]); - await const KernelSnapshotProgram().build(androidEnvironment + await const KernelSnapshot().build(androidEnvironment ..defines[kTargetPlatform] = getNameForTargetPlatform(TargetPlatform.darwin) ..defines[kBuildMode] = BuildMode.debug.cliName ..defines[kTrackWidgetCreation] = 'false' @@ -380,7 +359,7 @@ native-assets: expect(processManager, hasNoRemainingExpectations); }); - testWithoutContext('KernelSnapshotProgram does use track widget creation on debug builds', () async { + testWithoutContext('KernelSnapshot does use track widget creation on debug builds', () async { fileSystem.file('.dart_tool/package_config.json') ..createSync(recursive: true) ..writeAsStringSync('{"configVersion": 2, "packages":[]}'); @@ -415,92 +394,22 @@ native-assets: '--packages', '/.dart_tool/package_config.json', '--output-dill', - '$build/program.dill', + '$build/app.dill', '--depfile', '$build/kernel_snapshot_program.d', '--incremental', '--initialize-from-dill', - '$build/program.dill', + '$build/app.dill', '--verbosity=error', 'file:///lib/main.dart', - ], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey /build/653e11a8e6908714056a57cd6b4f602a/program.dill 0\n'), + ], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey /build/653e11a8e6908714056a57cd6b4f602a/app.dill 0\n'), ]); - await const KernelSnapshotProgram().build(testEnvironment); + await const KernelSnapshot().build(testEnvironment); expect(processManager, hasNoRemainingExpectations); }); - for (final BuildMode buildMode in [BuildMode.debug, BuildMode.release]) { - for (final bool empty in [true, false]) { - final String testName = empty ? 'empty' : 'non empty'; - testWithoutContext('KernelSnapshotNativeAssets ${buildMode.name} $testName', () async { - fileSystem.file('.dart_tool/package_config.json') - ..createSync(recursive: true) - ..writeAsStringSync('{"configVersion": 2, "packages":[]}'); - androidEnvironment.buildDir.childFile(InstallCodeAssets.nativeAssetsFilename) - ..createSync(recursive: true) - ..writeAsStringSync(empty ? emptyNativeAssets : nonEmptyNativeAssets); - final String build = androidEnvironment.buildDir.path; - final String flutterPatchedSdkPath = artifacts.getArtifactPath( - Artifact.flutterPatchedSdkPath, - platform: TargetPlatform.darwin, - mode: buildMode, - ); - processManager.addCommands([ - if (!empty) - FakeCommand(command: [ - artifacts.getArtifactPath(Artifact.engineDartAotRuntime), - artifacts.getArtifactPath(Artifact.frontendServerSnapshotForEngineDartSdk), - '--sdk-root', - '$flutterPatchedSdkPath/', - '--target=flutter', - '--no-print-incremental-dependencies', - ...buildModeOptions(buildMode, []), - '--no-link-platform', - if (buildMode == BuildMode.release) ...['--aot', '--tfa'], - '--packages', - '/.dart_tool/package_config.json', - '--output-dill', - '$build/native_assets.dill', - '--native-assets', - '$build/${InstallCodeAssets.nativeAssetsFilename}', - '--verbosity=error', - '--native-assets-only', - ], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'), - ]); - - await const KernelSnapshotNativeAssets().build(androidEnvironment - ..defines[kTargetPlatform] = getNameForTargetPlatform(TargetPlatform.darwin) - ..defines[kBuildMode] = buildMode.cliName - ); - - expect(processManager, hasNoRemainingExpectations); - }); - } - } - - for (final bool empty in [true, false]) { - final String testName = empty ? 'empty' : 'non empty'; - testWithoutContext('KernelSnapshot native assets $testName', () async { - const List programDillBytes = [1, 2, 3, 4]; - androidEnvironment.buildDir.childFile('program.dill') - ..createSync(recursive: true) - ..writeAsBytesSync(programDillBytes); - final List nativeAssetsDillBytes = empty ? [] : [5, 6, 7, 8]; - androidEnvironment.buildDir.childFile('native_assets.dill') - ..createSync(recursive: true) - ..writeAsBytesSync(nativeAssetsDillBytes); - - await const KernelSnapshot().build(androidEnvironment); - - expect( - androidEnvironment.buildDir.childFile('app.dill').readAsBytesSync(), - equals([...programDillBytes, ...nativeAssetsDillBytes]), - ); - }); - } - testUsingContext('AotElfProfile Produces correct output directory', () async { final String build = androidEnvironment.buildDir.path; processManager.addCommands([ @@ -520,6 +429,7 @@ native-assets: ]), ]); androidEnvironment.buildDir.childFile('app.dill').createSync(recursive: true); + androidEnvironment.buildDir.childFile('native_assets.json').createSync(); await const AotElfProfile(TargetPlatform.android_arm).build(androidEnvironment); @@ -548,6 +458,7 @@ native-assets: ]), ]); androidEnvironment.buildDir.childFile('app.dill').createSync(recursive: true); + androidEnvironment.buildDir.childFile('native_assets.json').createSync(); await const AotElfRelease(TargetPlatform.android_arm).build(androidEnvironment); diff --git a/packages/flutter_tools/test/general.shard/build_system/targets/ios_test.dart b/packages/flutter_tools/test/general.shard/build_system/targets/ios_test.dart index cbf7635d6fa..3dadc553c78 100644 --- a/packages/flutter_tools/test/general.shard/build_system/targets/ios_test.dart +++ b/packages/flutter_tools/test/general.shard/build_system/targets/ios_test.dart @@ -205,6 +205,7 @@ void main() { .createSync(recursive: true); // App kernel environment.buildDir.childFile('app.dill').createSync(recursive: true); + environment.buildDir.childFile('native_assets.json').createSync(); // Stub framework environment.buildDir .childDirectory('App.framework') @@ -285,6 +286,7 @@ void main() { fileSystem.file('shader.glsl').writeAsStringSync('test'); // App kernel environment.buildDir.childFile('app.dill').createSync(recursive: true); + environment.buildDir.childFile('native_assets.json').createSync(); // Stub framework environment.buildDir .childDirectory('App.framework') @@ -360,6 +362,7 @@ void main() { .childDirectory('App.framework') .childFile('App') .createSync(recursive: true); + environment.buildDir.childFile('native_assets.json').createSync(); // Input dSYM environment.buildDir @@ -425,6 +428,7 @@ void main() { .childDirectory('App.framework') .childFile('App') .createSync(recursive: true); + environment.buildDir.childFile('native_assets.json').createSync(); final Directory frameworkDirectory = environment.outputDir.childDirectory('App.framework'); final File frameworkDirectoryBinary = frameworkDirectory.childFile('App'); diff --git a/packages/flutter_tools/test/general.shard/build_system/targets/linux_test.dart b/packages/flutter_tools/test/general.shard/build_system/targets/linux_test.dart index e6b21fc9cd9..8e64d0a4da6 100644 --- a/packages/flutter_tools/test/general.shard/build_system/targets/linux_test.dart +++ b/packages/flutter_tools/test/general.shard/build_system/targets/linux_test.dart @@ -116,6 +116,7 @@ void main() { // Create input files. testEnvironment.buildDir.childFile('app.dill').createSync(); + testEnvironment.buildDir.childFile('native_assets.json').createSync(); fileSystem.file('bundle.sksl').writeAsStringSync(json.encode( { 'engineRevision': '2', @@ -169,6 +170,7 @@ void main() { // Create input files. testEnvironment.buildDir.childFile('app.so').createSync(); + testEnvironment.buildDir.childFile('native_assets.json').createSync(); await const LinuxAotBundle(AotElfProfile(TargetPlatform.linux_x64)).build(testEnvironment); await const ProfileBundleLinuxAssets(TargetPlatform.linux_x64).build(testEnvironment); @@ -208,6 +210,7 @@ void main() { // Create input files. testEnvironment.buildDir.childFile('app.so').createSync(); + testEnvironment.buildDir.childFile('native_assets.json').createSync(); await const LinuxAotBundle(AotElfRelease(TargetPlatform.linux_x64)).build(testEnvironment); await const ReleaseBundleLinuxAssets(TargetPlatform.linux_x64).build(testEnvironment); diff --git a/packages/flutter_tools/test/general.shard/build_system/targets/macos_test.dart b/packages/flutter_tools/test/general.shard/build_system/targets/macos_test.dart index a9178c78036..53d4cf85a3a 100644 --- a/packages/flutter_tools/test/general.shard/build_system/targets/macos_test.dart +++ b/packages/flutter_tools/test/general.shard/build_system/targets/macos_test.dart @@ -418,6 +418,7 @@ void main() { fileSystem.file(inputKernel) ..createSync(recursive: true) ..writeAsStringSync('testing'); + environment.buildDir.childFile('native_assets.json').createSync(); await const DebugMacOSBundleFlutterAssets().build(environment); @@ -454,6 +455,9 @@ void main() { .createSync(recursive: true); fileSystem.file('${environment.buildDir.path}/App.framework/App') .createSync(recursive: true); + fileSystem + .file('${environment.buildDir.path}/native_assets.json') + .createSync(); await const ProfileMacOSBundleFlutterAssets().build(environment..defines[kBuildMode] = 'profile'); @@ -483,6 +487,9 @@ void main() { .createSync(recursive: true); fileSystem.file('${environment.buildDir.path}/App.framework.dSYM/Contents/Resources/DWARF/App') .createSync(recursive: true); + fileSystem + .file('${environment.buildDir.path}/native_assets.json') + .createSync(); await const ReleaseMacOSBundleFlutterAssets() .build(environment..defines[kBuildMode] = 'release'); @@ -504,6 +511,9 @@ void main() { final File inputFramework = fileSystem.file(fileSystem.path.join(environment.buildDir.path, 'App.framework', 'App')) ..createSync(recursive: true) ..writeAsStringSync('ABC'); + fileSystem + .file(environment.buildDir.childFile('native_assets.json')) + .createSync(); await const ProfileMacOSBundleFlutterAssets().build(environment..defines[kBuildMode] = 'profile'); final File outputFramework = fileSystem.file(fileSystem.path.join(environment.outputDir.path, 'App.framework', 'App')); @@ -529,6 +539,9 @@ void main() { .createSync(recursive: true); fileSystem.file(fileSystem.path.join(environment.buildDir.path, 'App.framework', 'App')) .createSync(recursive: true); + fileSystem + .file(environment.buildDir.childFile('native_assets.json')) + .createSync(); await const ReleaseMacOSBundleFlutterAssets().build(environment); expect(usage.events, contains(const TestUsageEvent('assemble', 'macos-archive', label: 'success'))); diff --git a/packages/flutter_tools/test/general.shard/build_system/targets/windows_test.dart b/packages/flutter_tools/test/general.shard/build_system/targets/windows_test.dart index 11b85dd995e..ca1510b67bd 100644 --- a/packages/flutter_tools/test/general.shard/build_system/targets/windows_test.dart +++ b/packages/flutter_tools/test/general.shard/build_system/targets/windows_test.dart @@ -136,6 +136,7 @@ void main() { ); environment.buildDir.childFile('app.dill').createSync(recursive: true); + environment.buildDir.childFile('native_assets.json').createSync(recursive: true); // sksl bundle fileSystem.file('bundle.sksl').writeAsStringSync(json.encode( { @@ -173,6 +174,7 @@ void main() { ); environment.buildDir.childFile('app.so').createSync(recursive: true); + environment.buildDir.childFile('native_assets.json').createSync(recursive: true); await const WindowsAotBundle(AotElfProfile(TargetPlatform.windows_x64)).build(environment); await const ProfileBundleWindowsAssets(TargetPlatform.windows_x64).build(environment); @@ -200,6 +202,7 @@ void main() { ); environment.buildDir.childFile('app.so').createSync(recursive: true); + environment.buildDir.childFile('native_assets.json').createSync(recursive: true); await const WindowsAotBundle(AotElfRelease(TargetPlatform.windows_x64)).build(environment); await const ReleaseBundleWindowsAssets(TargetPlatform.windows_x64).build(environment); diff --git a/packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart index 1a26d82d227..83722c77b43 100644 --- a/packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart @@ -116,7 +116,7 @@ void main() { ]), ); - expect(environment.buildDir.childFile('native_assets.yaml'), exists); + expect(environment.buildDir.childFile('native_assets.json'), exists); expect(buildRunner.buildInvocations, 1); expect( buildRunner.linkInvocations, diff --git a/packages/flutter_tools/test/general.shard/isolated/build_system/targets/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/build_system/targets/native_assets_test.dart index 39be84f77f4..c4312cc8c02 100644 --- a/packages/flutter_tools/test/general.shard/isolated/build_system/targets/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/build_system/targets/native_assets_test.dart @@ -104,7 +104,7 @@ void main() { for (final bool isNativeAssetsEnabled in [true, false]) { final String postFix = isNativeAssetsEnabled ? 'enabled' : 'disabled'; testUsingContext( - 'Successful native_assets.yaml and native_assets.d creation with feature $postFix', + 'Successful native_assets.json and native_assets.d creation with feature $postFix', overrides: { FileSystem: () => fileSystem, ProcessManager: () => processManager, diff --git a/packages/flutter_tools/test/general.shard/isolated/fake_native_assets_build_runner.dart b/packages/flutter_tools/test/general.shard/isolated/fake_native_assets_build_runner.dart index e8dc48bfe3a..21f70ecad25 100644 --- a/packages/flutter_tools/test/general.shard/isolated/fake_native_assets_build_runner.dart +++ b/packages/flutter_tools/test/general.shard/isolated/fake_native_assets_build_runner.dart @@ -2,12 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:file/file.dart'; -import 'package:flutter_tools/src/base/logger.dart'; -import 'package:flutter_tools/src/build_info.dart' hide BuildMode; import 'package:flutter_tools/src/isolated/native_assets/native_assets.dart'; -import 'package:flutter_tools/src/resident_runner.dart'; -import 'package:flutter_tools/src/run_hot.dart'; import 'package:native_assets_builder/native_assets_builder.dart'; import 'package:native_assets_cli/code_assets_builder.dart'; import 'package:package_config/package_config_types.dart'; @@ -23,7 +18,6 @@ class FakeFlutterNativeAssetsBuildRunner this.packagesWithNativeAssetsResult = const [], this.onBuild, this.onLink, - this.buildDryRunResult = const FakeFlutterNativeAssetsBuilderResult(), this.buildResult = const FakeFlutterNativeAssetsBuilderResult(), this.linkResult = const FakeFlutterNativeAssetsBuilderResult(), CCompilerConfig? cCompilerConfigResult, @@ -36,14 +30,12 @@ class FakeFlutterNativeAssetsBuildRunner final LinkResult? Function(LinkConfig)? onLink; final BuildResult? buildResult; final LinkResult? linkResult; - final BuildDryRunResult? buildDryRunResult; final bool hasPackageConfigResult; final List packagesWithNativeAssetsResult; final CCompilerConfig cCompilerConfigResult; final CCompilerConfig ndkCCompilerConfigResult; int buildInvocations = 0; - int buildDryRunInvocations = 0; int linkInvocations = 0; int hasPackageConfigInvocations = 0; int packagesWithNativeAssetsInvocations = 0; @@ -128,19 +120,6 @@ class FakeFlutterNativeAssetsBuildRunner return result; } - @override - Future buildDryRun({ - required List supportedAssetTypes, - required ConfigCreator configCreator, - required BuildValidator buildValidator, - required bool includeParentEnvironment, - required OS targetOS, - required Uri workingDirectory, - }) async { - buildDryRunInvocations++; - return buildDryRunResult; - } - @override Future hasPackageConfig() async { hasPackageConfigInvocations++; @@ -161,7 +140,7 @@ class FakeFlutterNativeAssetsBuildRunner } final class FakeFlutterNativeAssetsBuilderResult - implements BuildResult, BuildDryRunResult, LinkResult { + implements BuildResult, LinkResult { const FakeFlutterNativeAssetsBuilderResult({ this.encodedAssets = const [], this.encodedAssetsForLinking = const >{}, @@ -197,30 +176,3 @@ final class FakeFlutterNativeAssetsBuilderResult @override final List dependencies; } - -class FakeHotRunnerNativeAssetsBuilder implements HotRunnerNativeAssetsBuilder { - FakeHotRunnerNativeAssetsBuilder(this.buildRunner); - - final FlutterNativeAssetsBuildRunner buildRunner; - - @override - Future dryRun({ - required Uri projectUri, - required FileSystem fileSystem, - required List flutterDevices, - required String packageConfigPath, - required PackageConfig packageConfig, - required Logger logger, - }) { - final List targetPlatforms = flutterDevices - .map((FlutterDevice d) => d.targetPlatform) - .nonNulls - .toList(); - return runFlutterSpecificDartDryRunOnPlatforms( - projectUri: projectUri, - fileSystem: fileSystem, - buildRunner: buildRunner, - targetPlatforms: targetPlatforms, - ); - } -} diff --git a/packages/flutter_tools/test/general.shard/isolated/hot_test.dart b/packages/flutter_tools/test/general.shard/isolated/hot_test.dart deleted file mode 100644 index 60ee84f6b0a..00000000000 --- a/packages/flutter_tools/test/general.shard/isolated/hot_test.dart +++ /dev/null @@ -1,182 +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:file/memory.dart'; -import 'package:flutter_tools/src/artifacts.dart'; -import 'package:flutter_tools/src/base/file_system.dart'; -import 'package:flutter_tools/src/base/platform.dart'; -import 'package:flutter_tools/src/build_info.dart'; -import 'package:flutter_tools/src/devfs.dart'; -import 'package:flutter_tools/src/device.dart'; -import 'package:flutter_tools/src/features.dart'; -import 'package:flutter_tools/src/resident_devtools_handler.dart'; -import 'package:flutter_tools/src/resident_runner.dart'; -import 'package:flutter_tools/src/run_hot.dart'; -import 'package:native_assets_cli/code_assets_builder.dart'; -import 'package:package_config/package_config.dart'; -import 'package:unified_analytics/unified_analytics.dart'; - -import '../../src/common.dart'; -import '../../src/context.dart'; -import '../../src/fakes.dart'; -import '../hot_shared.dart'; -import 'fake_native_assets_build_runner.dart'; - -void main() { - group('native assets', () { - late TestHotRunnerConfig testingConfig; - late MemoryFileSystem fileSystem; - late FakeAnalytics fakeAnalytics; - - setUp(() { - fileSystem = MemoryFileSystem.test(); - testingConfig = TestHotRunnerConfig( - successfulHotRestartSetup: true, - ); - fakeAnalytics = getInitializedFakeAnalyticsInstance( - fs: fileSystem, - fakeFlutterVersion: FakeFlutterVersion(), - ); - }); - testUsingContext('native assets restart', () async { - final FakeDevice device = FakeDevice(); - final FakeFlutterDevice fakeFlutterDevice = FakeFlutterDevice(device); - final List devices = [ - fakeFlutterDevice, - ]; - - fakeFlutterDevice.updateDevFSReportCallback = () async => UpdateFSReport( - success: true, - invalidatedSourcesCount: 6, - syncedBytes: 8, - scannedSourcesCount: 16, - compileDuration: const Duration(seconds: 16), - transferDuration: const Duration(seconds: 32), - ); - - (fakeFlutterDevice.devFS! as FakeDevFs).baseUri = Uri.parse('file:///base_uri'); - - final FakeFlutterNativeAssetsBuildRunner buildRunner = FakeFlutterNativeAssetsBuildRunner( - packagesWithNativeAssetsResult: [ - Package('bar', fileSystem.currentDirectory.uri), - ], - buildDryRunResult: FakeFlutterNativeAssetsBuilderResult.fromAssets( - codeAssets: [ - CodeAsset( - package: 'bar', - name: 'bar.dart', - linkMode: DynamicLoadingBundled(), - os: OS.macOS, - architecture: Architecture.arm64, - file: Uri.file('bar.dylib'), - ), - CodeAsset( - package: 'bar', - name: 'bar.dart', - linkMode: DynamicLoadingBundled(), - os: OS.macOS, - architecture: Architecture.x64, - file: Uri.file('bar.dylib'), - ), - ], - ), - ); - - final HotRunner hotRunner = HotRunner( - devices, - debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), - target: 'main.dart', - devtoolsHandler: createNoOpHandler, - nativeAssetsBuilder: FakeHotRunnerNativeAssetsBuilder(buildRunner), - analytics: fakeAnalytics, - ); - final OperationResult result = await hotRunner.restart(fullRestart: true); - expect(result.isOk, true); - // Hot restart does not require rerunning anything for native assets. - // The previous native assets mapping should be used. - expect(buildRunner.buildInvocations, 0); - expect(buildRunner.buildDryRunInvocations, 0); - expect(buildRunner.linkInvocations, 0); - expect(buildRunner.hasPackageConfigInvocations, 0); - expect(buildRunner.packagesWithNativeAssetsInvocations, 0); - }, overrides: { - HotRunnerConfig: () => testingConfig, - Artifacts: () => Artifacts.test(), - FileSystem: () => fileSystem, - Platform: () => FakePlatform(), - ProcessManager: () => FakeProcessManager.empty(), - FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true, isMacOSEnabled: true), - }); - - testUsingContext('native assets run unsupported', () async { - final FakeDevice device = FakeDevice(targetPlatform: TargetPlatform.fuchsia_arm64); - final FakeFlutterDevice fakeFlutterDevice = FakeFlutterDevice(device); - final List devices = [ - fakeFlutterDevice, - ]; - - fakeFlutterDevice.updateDevFSReportCallback = () async => UpdateFSReport( - success: true, - invalidatedSourcesCount: 6, - syncedBytes: 8, - scannedSourcesCount: 16, - compileDuration: const Duration(seconds: 16), - transferDuration: const Duration(seconds: 32), - ); - - (fakeFlutterDevice.devFS! as FakeDevFs).baseUri = Uri.parse('file:///base_uri'); - - final FakeFlutterNativeAssetsBuildRunner buildRunner = FakeFlutterNativeAssetsBuildRunner( - packagesWithNativeAssetsResult: [ - Package('bar', fileSystem.currentDirectory.uri), - ], - buildDryRunResult: FakeFlutterNativeAssetsBuilderResult.fromAssets( - codeAssets: [ - CodeAsset( - package: 'bar', - name: 'bar.dart', - linkMode: DynamicLoadingBundled(), - os: OS.macOS, - architecture: Architecture.arm64, - file: Uri.file('bar.dylib'), - ), - CodeAsset( - package: 'bar', - name: 'bar.dart', - linkMode: DynamicLoadingBundled(), - os: OS.macOS, - architecture: Architecture.x64, - file: Uri.file('bar.dylib'), - ), - ], - ), - ); - - final HotRunner hotRunner = HotRunner( - devices, - debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), - target: 'main.dart', - devtoolsHandler: createNoOpHandler, - nativeAssetsBuilder: FakeHotRunnerNativeAssetsBuilder(buildRunner), - analytics: fakeAnalytics, - ); - expect( - () => hotRunner.run(), - throwsToolExit( message: - 'Package(s) bar require the native assets feature. ' - 'This feature has not yet been implemented for `TargetPlatform.fuchsia_arm64`. ' - 'For more info see https://github.com/flutter/flutter/issues/129757.', - ) - ); - - }, overrides: { - HotRunnerConfig: () => testingConfig, - Artifacts: () => Artifacts.test(), - FileSystem: () => fileSystem, - Platform: () => FakePlatform(), - ProcessManager: () => FakeProcessManager.empty(), - FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true, isMacOSEnabled: true), - }); - }); -} diff --git a/packages/flutter_tools/test/general.shard/isolated/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/native_assets_test.dart index 64b3957617d..003ca4f9072 100644 --- a/packages/flutter_tools/test/general.shard/isolated/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/native_assets_test.dart @@ -47,26 +47,6 @@ void main() { projectUri = environment.projectDir.uri; }); - testUsingContext('dry run with no package config', overrides: { - ProcessManager: () => FakeProcessManager.empty(), - }, () async { - expect( - await runFlutterSpecificDartDryRunOnPlatforms( - projectUri: projectUri, - fileSystem: fileSystem, - targetPlatforms: [TargetPlatform.windows_x64], - buildRunner: FakeFlutterNativeAssetsBuildRunner( - hasPackageConfigResult: false, - ), - ), - null, - ); - expect( - (globals.logger as BufferLogger).traceText, - contains('No package config found. Skipping native assets compilation.'), - ); - }); - testUsingContext('build with no package config', overrides: { ProcessManager: () => FakeProcessManager.empty(), }, () async { @@ -87,97 +67,6 @@ void main() { ); }); - testUsingContext('dry run for multiple OSes with no package config', overrides: { - ProcessManager: () => FakeProcessManager.empty(), - }, () async { - await runFlutterSpecificDartDryRunOnPlatforms( - projectUri: projectUri, - fileSystem: fileSystem, - targetPlatforms: [ - TargetPlatform.windows_x64, - TargetPlatform.darwin, - TargetPlatform.ios, - ], - buildRunner: FakeFlutterNativeAssetsBuildRunner( - hasPackageConfigResult: false, - ), - ); - expect( - (globals.logger as BufferLogger).traceText, - contains('No package config found. Skipping native assets compilation.'), - ); - }); - - testUsingContext('dry run with assets but not enabled', overrides: { - ProcessManager: () => FakeProcessManager.empty(), - }, () async { - final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); - await packageConfig.parent.create(); - await packageConfig.create(); - expect( - () => runFlutterSpecificDartDryRunOnPlatforms( - projectUri: projectUri, - fileSystem: fileSystem, - targetPlatforms: [TargetPlatform.windows_x64], - buildRunner: FakeFlutterNativeAssetsBuildRunner( - packagesWithNativeAssetsResult: [ - Package('bar', projectUri), - ], - ), - ), - throwsToolExit( - message: 'Package(s) bar require the native assets feature to be enabled. ' - 'Enable using `flutter config --enable-native-assets`.', - ), - ); - }); - - testUsingContext('dry run with assets', overrides: { - FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), - ProcessManager: () => FakeProcessManager.empty(), - }, () async { - final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); - await packageConfig.parent.create(); - await packageConfig.create(); - final FakeFlutterNativeAssetsBuildRunner buildRunner = FakeFlutterNativeAssetsBuildRunner( - packagesWithNativeAssetsResult: [ - Package('bar', projectUri), - ], - buildDryRunResult: FakeFlutterNativeAssetsBuilderResult.fromAssets( - codeAssets: [ - CodeAsset( - package: 'bar', - name: 'bar.dart', - linkMode: DynamicLoadingBundled(), - os: OS.windows, - file: Uri.file('bar.dll'), - ), - ], - ), - ); - final Uri? nativeAssetsYaml = await runFlutterSpecificDartDryRunOnPlatforms( - projectUri: projectUri, - fileSystem: fileSystem, - targetPlatforms: [TargetPlatform.windows_x64], - buildRunner: buildRunner, - ); - expect( - (globals.logger as BufferLogger).traceText, - stringContainsInOrder([ - 'Dry running native assets for windows.', - 'Dry running native assets for windows done.', - ]), - ); - expect( - nativeAssetsYaml, - projectUri.resolve('build/native_assets/windows/${InstallCodeAssets.nativeAssetsFilename}'), - ); - expect( - await fileSystem.file(nativeAssetsYaml).readAsString(), - contains('package:bar/bar.dart'), - ); - expect(buildRunner.buildDryRunInvocations, 1); - }); testUsingContext('Native assets: non-bundled libraries require no copying', overrides: { FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), @@ -185,7 +74,7 @@ void main() { }, () async { final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); - final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.yaml').uri; + final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.json').uri; await packageConfig.parent.create(); await packageConfig.create(); @@ -302,33 +191,6 @@ void main() { ); }); - testUsingContext('Native assets dry run error', overrides: { - FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), - ProcessManager: () => FakeProcessManager.empty(), - }, () async { - final File packageConfig = - environment.projectDir.childFile('.dart_tool/package_config.json'); - await packageConfig.parent.create(); - await packageConfig.create(); - expect( - () => runFlutterSpecificDartDryRunOnPlatforms( - projectUri: projectUri, - fileSystem: fileSystem, - targetPlatforms: [TargetPlatform.windows_x64], - buildRunner: FakeFlutterNativeAssetsBuildRunner( - packagesWithNativeAssetsResult: [ - Package('bar', projectUri), - ], - buildDryRunResult: null, - ), - ), - throwsToolExit( - message: - 'Building (dry run) native assets failed. See the logs for more details.', - ), - ); - }); - testUsingContext('Native assets build error', overrides: { FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), ProcessManager: () => FakeProcessManager.empty(), diff --git a/packages/flutter_tools/test/general.shard/isolated/resident_runner_test.dart b/packages/flutter_tools/test/general.shard/isolated/resident_runner_test.dart index aec25320856..ef6af344f8a 100644 --- a/packages/flutter_tools/test/general.shard/isolated/resident_runner_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/resident_runner_test.dart @@ -17,7 +17,6 @@ import '../../src/fake_vm_services.dart'; import '../../src/fakes.dart'; import '../../src/testbed.dart'; import '../resident_runner_helpers.dart'; -import 'fake_native_assets_build_runner.dart'; void main() { late Testbed testbed; @@ -55,8 +54,7 @@ void main() { ]); globals.fs .file(globals.fs.path.join('lib', 'main.dart')) - .createSync(recursive: true); - final FakeFlutterNativeAssetsBuildRunner buildRunner = FakeFlutterNativeAssetsBuildRunner(); + .createSync(recursive: true); final HotRunner residentRunner = HotRunner( [ flutterDevice, @@ -71,7 +69,6 @@ void main() { )), target: 'main.dart', devtoolsHandler: createNoOpHandler, - nativeAssetsBuilder: FakeHotRunnerNativeAssetsBuilder(buildRunner), analytics: FakeAnalytics(), nativeAssetsYamlFile: 'foo.yaml', ); @@ -79,12 +76,6 @@ void main() { final int result = await residentRunner.run(); expect(result, 0); - expect(buildRunner.buildInvocations, 0); - expect(buildRunner.buildDryRunInvocations, 0); - expect(buildRunner.linkInvocations, 0); - expect(buildRunner.hasPackageConfigInvocations, 0); - expect(buildRunner.packagesWithNativeAssetsInvocations, 0); - expect(residentCompiler.recompileCalled, true); expect(residentCompiler.receivedNativeAssetsYaml, globals.fs.path.toUri('foo.yaml')); }), diff --git a/packages/flutter_tools/test/general.shard/isolated/windows/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/windows/native_assets_test.dart index 9f9b6db1c0f..ef29a21ebe2 100644 --- a/packages/flutter_tools/test/general.shard/isolated/windows/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/windows/native_assets_test.dart @@ -145,7 +145,10 @@ void main() { 'package:bar/bar.dart', if (flutterTester) // Tests run on host system, so the have the full path on the system. - projectUri.resolve('build/native_assets/$expectedDirectory/bar.dll').toFilePath() + projectUri + .resolve('build/native_assets/$expectedDirectory/bar.dll') + .toFilePath() + .replaceAll(r'\', r'\\') // Undo JSON string escaping. else // Apps are a bundle with the dylibs on their dlopen path. 'bar.dll', From 5c8841326628019c6e339be8488191c6d728c9c7 Mon Sep 17 00:00:00 2001 From: Flutter GitHub Bot Date: Wed, 27 Nov 2024 11:21:32 -0500 Subject: [PATCH 231/386] Marks Mac_benchmark hello_world_macos__compile to be flaky (#159543) Issue link: https://github.com/flutter/flutter/issues/159542 Co-authored-by: Chris Bracken --- .ci.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.ci.yaml b/.ci.yaml index 0a61bd3ed8b..03830b5476f 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -4028,6 +4028,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 From 8343e9b47eb90c15c90473eeab0aa33611e1ff3d Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Wed, 27 Nov 2024 12:43:21 -0500 Subject: [PATCH 232/386] Roll Flutter Engine from 4121287c360a to ed4e13cefb45 (1 revision) (#159559) https://github.com/flutter/engine/compare/4121287c360a...ed4e13cefb45 2024-11-27 chris@bracken.jp Reland: iOS: Eliminate global in platformviews controller (flutter/engine#56831) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index b588c707cc9..89ce55f7851 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -4121287c360a096d2ba3161be66021bfe0c4f8b6 +ed4e13cefb45d95404b148afd3e39ec678160357 From d686ad3b28e050fb7177f4ef01d0f68bbf3f0641 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Wed, 27 Nov 2024 13:12:20 -0500 Subject: [PATCH 233/386] Roll Packages from 8ecf4b010143 to e6932b77a183 (3 revisions) (#159561) https://github.com/flutter/packages/compare/8ecf4b010143...e6932b77a183 2024-11-26 stuartmorgan@google.com [flutter_svg] Adopt code excerpts (flutter/packages#8181) 2024-11-26 brackenavaron@gmail.com [flutter_markdown] fix invalid URI's causing unhandled image errors (flutter/packages#8058) 2024-11-26 10687576+bparrishMines@users.noreply.github.com [ci][webview_flutter_android] Manual Roll and skip tests (flutter/packages#8186) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-packages-flutter-autoroll Please CC flutter-ecosystem@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/flutter_packages.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/flutter_packages.version b/bin/internal/flutter_packages.version index 44e1586382f..f6d4b7f01e7 100644 --- a/bin/internal/flutter_packages.version +++ b/bin/internal/flutter_packages.version @@ -1 +1 @@ -8ecf4b010143d331461aa466f371a4f6f7f58d83 +e6932b77a183661e19136993094c3cc268900562 From fdc666158e9f3b6fc3520a6d19227d2e27c76be0 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Wed, 27 Nov 2024 13:48:41 -0500 Subject: [PATCH 234/386] Roll Flutter Engine from ed4e13cefb45 to ba112add5d98 (1 revision) (#159563) https://github.com/flutter/engine/compare/ed4e13cefb45...ba112add5d98 2024-11-27 jonahwilliams@google.com [Impeller] dont use dynamic shader metadata path for precompiled shaders. (flutter/engine#56827) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 89ce55f7851..e8da2d64597 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -ed4e13cefb45d95404b148afd3e39ec678160357 +ba112add5d987b446c164f71642be5b7039ab95f From d541354936be9ddc999db480cd35ecb373ecda4b Mon Sep 17 00:00:00 2001 From: Aziz Chebbi <60013060+azizChebbi@users.noreply.github.com> Date: Thu, 28 Nov 2024 02:04:08 +0100 Subject: [PATCH 235/386] Fix: Announce only the first error message for better accessibility (#156399) ## Issue This pull request addresses an accessibility issue where all form error messages were concatenated and announced simultaneously, overwhelming users relying on screen readers like VoiceOver and TalkBack. This is the issue link: https://github.com/flutter/flutter/issues/156340 ## Update The change ensures that only the first error message is announced, providing a more manageable and user-friendly experience. ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. --------- Co-authored-by: chunhtai <47866232+chunhtai@users.noreply.github.com> --- packages/flutter/lib/src/widgets/form.dart | 5 +- packages/flutter/test/widgets/form_test.dart | 68 +++++++++++--------- 2 files changed, 42 insertions(+), 31 deletions(-) diff --git a/packages/flutter/lib/src/widgets/form.dart b/packages/flutter/lib/src/widgets/form.dart index 8fe5cf786b1..dac0bf9c8d2 100644 --- a/packages/flutter/lib/src/widgets/form.dart +++ b/packages/flutter/lib/src/widgets/form.dart @@ -357,7 +357,10 @@ class FormState extends State { if (!validateOnFocusChange || !field._focusNode.hasFocus) { final bool isFieldValid = field.validate(); hasError = !isFieldValid || hasError; - errorMessage += field.errorText ?? ''; + // 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); } diff --git a/packages/flutter/test/widgets/form_test.dart b/packages/flutter/test/widgets/form_test.dart index 5a3117d47d7..1fc97db56f9 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>(); From c519383bcccfd73657f20887f9fdb0c346fb2da7 Mon Sep 17 00:00:00 2001 From: Harry Terkelsen <1961493+harryterkelsen@users.noreply.github.com> Date: Wed, 27 Nov 2024 17:15:59 -0800 Subject: [PATCH 236/386] [web] On the web platform, use an tag to show an image if it can't be accessed with CORS (#157755) When using `Image.network`, if the given URL points to an image that is cross-origin and not set up to allow CORS access, then we are unable to make a [ui.Image] from it. In this case, render the image using a platform view. This is the last remaining checklist item for https://github.com/flutter/flutter/issues/145954 Fixes https://github.com/flutter/flutter/issues/149843 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- .../lib/src/painting/_network_image_web.dart | 295 +++++++++++--- .../lib/src/painting/_web_image_info_io.dart | 40 ++ .../lib/src/painting/_web_image_info_web.dart | 70 ++++ .../lib/src/painting/image_stream.dart | 19 + packages/flutter/lib/src/web.dart | 19 + .../lib/src/widgets/_web_image_io.dart | 50 +++ .../lib/src/widgets/_web_image_web.dart | 382 ++++++++++++++++++ packages/flutter/lib/src/widgets/image.dart | 63 ++- .../painting/_network_image_test_web.dart | 215 +++++++++- .../test/painting/_test_http_request.dart | 66 +++ .../image_provider_network_image_test.dart | 2 +- 11 files changed, 1131 insertions(+), 90 deletions(-) create mode 100644 packages/flutter/lib/src/painting/_web_image_info_io.dart create mode 100644 packages/flutter/lib/src/painting/_web_image_info_web.dart create mode 100644 packages/flutter/lib/src/widgets/_web_image_io.dart create mode 100644 packages/flutter/lib/src/widgets/_web_image_web.dart 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/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/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/_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/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/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); }); From def629d041b0fbd2e81be938f7b67bd6d47a726a Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Wed, 27 Nov 2024 20:46:10 -0500 Subject: [PATCH 237/386] Roll Flutter Engine from ba112add5d98 to dd0ef5ba7d9a (2 revisions) (#159574) https://github.com/flutter/engine/compare/ba112add5d98...dd0ef5ba7d9a 2024-11-27 skia-flutter-autoroll@skia.org Roll Fuchsia Test Scripts from OA7UxNZkbxCRfr80A... to VilXq4eGH5A24wRWA... (flutter/engine#56846) 2024-11-27 lauren@selfisekai.rocks IWYU: add some missing includes failing with libstdc++13/14 (flutter/engine#56822) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index e8da2d64597..ebd8888838d 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -ba112add5d987b446c164f71642be5b7039ab95f +dd0ef5ba7d9a32fc99f0df267569c7dc13cda8bc From 0e2a9c02132917729bc138702365476be2a60d5c Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Thu, 28 Nov 2024 01:02:25 -0500 Subject: [PATCH 238/386] Roll Flutter Engine from dd0ef5ba7d9a to d7c0bcfe7a30 (1 revision) (#159579) https://github.com/flutter/engine/compare/dd0ef5ba7d9a...d7c0bcfe7a30 2024-11-28 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from u0agumUB4Ag6cTiKk... to oJzuSXcrUmaw5Ck2g... (flutter/engine#56853) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from u0agumUB4Ag6 to oJzuSXcrUmaw If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index ebd8888838d..cc185f3044e 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -dd0ef5ba7d9a32fc99f0df267569c7dc13cda8bc +d7c0bcfe7a30408b0722c9d47d8b0b1e4cdb9c81 diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index a481bc3034e..be859fd9c6a 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -u0agumUB4Ag6cTiKkU_LX30L_hjFI5-jFlHnArgyehwC +oJzuSXcrUmaw5Ck2gZW7hP5H95_HPDVv4fRSDD5ASfMC From 7453ffd22d55d70652c3e053cec4aee461f80fa2 Mon Sep 17 00:00:00 2001 From: Bruno Leroux Date: Thu, 28 Nov 2024 14:08:55 +0100 Subject: [PATCH 239/386] =?UTF-8?q?Revert=20"Fix=20Date=20picker=20overlay?= =?UTF-8?q?=20colors=20aren't=20applied=20on=20selected=20sta=E2=80=A6=20(?= =?UTF-8?q?#159583)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reverts https://github.com/flutter/flutter/pull/159203 because it depends on https://github.com/flutter/flutter/pull/159072 which was flagged as a perf regression in https://github.com/flutter/flutter/issues/159337. Reverting both PRs to see if the perf regression was really related to this change or was impacted by another change. See https://github.com/flutter/flutter/issues/159337#issuecomment-2504418480 for context. --- .../date_picker_theme_day_shape.0_test.dart | 27 +- .../src/material/calendar_date_picker.dart | 5 +- .../material/calendar_date_picker_test.dart | 2 +- .../test/material/date_picker_test.dart | 354 ++---------------- .../test/material/date_picker_theme_test.dart | 29 +- 5 files changed, 53 insertions(+), 364 deletions(-) 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 cbaa88f15f3..dc239d90494 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,15 +14,6 @@ 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(), ); @@ -30,13 +21,21 @@ 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); @@ -44,8 +43,12 @@ 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/packages/flutter/lib/src/material/calendar_date_picker.dart b/packages/flutter/lib/src/material/calendar_date_picker.dart index 20f82a05d3b..6c96ec343ee 100644 --- a/packages/flutter/lib/src/material/calendar_date_picker.dart +++ b/packages/flutter/lib/src/material/calendar_date_picker.dart @@ -20,7 +20,6 @@ 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'; @@ -1057,7 +1056,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(); @@ -1112,7 +1111,7 @@ class _DayState extends State<_Day> { shape: dayShape, ); - Widget dayWidget = Ink( + Widget dayWidget = DecoratedBox( decoration: decoration, child: Center( child: Text(localizations.formatDecimal(widget.day.day), style: dayStyle?.apply(color: dayForegroundColor)), diff --git a/packages/flutter/test/material/calendar_date_picker_test.dart b/packages/flutter/test/material/calendar_date_picker_test.dart index 20edff6c3b5..d166040f844 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()..circle(radius: 35.0, color: theme.colorScheme.onSurfaceVariant.withOpacity(0.08))); + expect(inkFeatures, paints..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/date_picker_test.dart b/packages/flutter/test/material/date_picker_test.dart index 810fa5e2cf2..380372d0390 100644 --- a/packages/flutter/test/material/date_picker_test.dart +++ b/packages/flutter/test/material/date_picker_test.dart @@ -132,21 +132,6 @@ 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 { @@ -1279,170 +1264,43 @@ void main() { await tester.pump(); const Color todayColor = Color(0xff2196f3); // default primary color expect( - findDayGridMaterial(tester), + Material.of(tester.element(find.text('2'))), // 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 hovered 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.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(); - 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 { + today = DateTime(2023, 5, 4); final ThemeData theme = ThemeData(); - await prepareDatePicker(tester, (Future date) async {}, theme: theme); + final bool material3 = theme.useMaterial3; + await prepareDatePicker(tester, (Future date) async { + await tester.pump(); - 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(); + // 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)), + ); - 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(); + // 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); }); testWidgets('Selecting date does not switch picker to year selection', (WidgetTester tester) async { @@ -2448,164 +2306,6 @@ 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(); - }); }); } diff --git a/packages/flutter/test/material/date_picker_theme_test.dart b/packages/flutter/test/material/date_picker_theme_test.dart index 28a328d364b..0f949a6a1e8 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(Ink) + matching: find.byType(DecoratedBox) ), ).decoration as ShapeDecoration?; } @@ -756,6 +756,7 @@ void main() { datePickerTheme: DatePickerThemeData( dayOverlayColor: dayOverlayColor, ), + useMaterial3: true, ), home: Directionality( textDirection: TextDirection.ltr, @@ -775,25 +776,17 @@ 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( - findDayGridMaterial(tester), + inkFeatures, paints - ..circle() // Today decoration. - ..circle() // Selected day decoration. ..circle(color: dayOverlayColor.resolve({MaterialState.hovered})), ); @@ -803,20 +796,16 @@ void main() { if (kIsWeb) { // An extra circle is painted on the web for the hovered state. expect( - findDayGridMaterial(tester), + inkFeatures, 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( - findDayGridMaterial(tester), + inkFeatures, paints - ..circle() // Today decoration. - ..circle() // Selected day decoration. ..circle(color: dayOverlayColor.resolve({MaterialState.hovered})) ..circle(color: dayOverlayColor.resolve({MaterialState.pressed})), ); @@ -833,10 +822,8 @@ void main() { // Test the focused overlay color. expect( - findDayGridMaterial(tester), + inkFeatures, paints - ..circle() // Today decoration. - ..circle() // Selected day decoration. ..circle(color: dayOverlayColor.resolve({MaterialState.focused})), ); }); From 08e26a3ffcd71b7b4e430a42d883240a20373af9 Mon Sep 17 00:00:00 2001 From: Bruno Leroux Date: Thu, 28 Nov 2024 15:35:20 +0100 Subject: [PATCH 240/386] Revert "Fix InkWell overlayColor resolution ignores selected state (#159072) (#159589) Reverts https://github.com/flutter/flutter/pull/159072 which was flagged as a perf regression in https://github.com/flutter/flutter/issues/159337. Reverting to see if the perf regression was really related to this change or was impacted by another change. See https://github.com/flutter/flutter/issues/159337#issuecomment-2504418480 for context. --- .../flutter/lib/src/material/ink_well.dart | 14 +- .../flutter/test/material/ink_well_test.dart | 136 +++--------------- 2 files changed, 27 insertions(+), 123 deletions(-) diff --git a/packages/flutter/lib/src/material/ink_well.dart b/packages/flutter/lib/src/material/ink_well.dart index 831776bdfb6..5912d2c38cc 100644 --- a/packages/flutter/lib/src/material/ink_well.dart +++ b/packages/flutter/lib/src/material/ink_well.dart @@ -1283,16 +1283,12 @@ class _InkResponseState extends State<_InkResponseStateWidget> assert(widget.debugCheckContext(context)); super.build(context); // See AutomaticKeepAliveClientMixin. - 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}; - 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); return switch (type) { // The pressed state triggers a ripple (ink splash), per the current // Material Design spec. A separate highlight is no longer used. diff --git a/packages/flutter/test/material/ink_well_test.dart b/packages/flutter/test/material/ink_well_test.dart index 9de987c3548..3cc961ccc10 100644 --- a/packages/flutter/test/material/ink_well_test.dart +++ b/packages/flutter/test/material/ink_well_test.dart @@ -11,10 +11,6 @@ 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 = []; @@ -174,7 +170,7 @@ void main() { await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(SizedBox))); await tester.pumpAndSettle(); - final RenderObject inkFeatures = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paints..rect(rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), color: const Color(0xff00ff00))); }); @@ -213,7 +209,7 @@ void main() { await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(SizedBox))); await tester.pumpAndSettle(); - final RenderObject inkFeatures = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paints..rect(rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), color: const Color(0xff00ff00))); }); @@ -244,7 +240,7 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderObject inkFeatures = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paintsExactlyCountTimes(#drawRect, 0)); focusNode.requestFocus(); await tester.pumpAndSettle(); @@ -293,7 +289,7 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderObject inkFeatures = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paintsExactlyCountTimes(#drawRect, 0)); focusNode.requestFocus(); await tester.pumpAndSettle(); @@ -331,101 +327,13 @@ void main() { )); await tester.pumpAndSettle(); final TestGesture gesture = await tester.startGesture(tester.getRect(find.byType(InkWell)).center); - final RenderObject inkFeatures = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); 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'); @@ -459,7 +367,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 = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paints..circle(x: 50, y: 50, color: splashColor)); await gesture.up(); focusNode.dispose(); @@ -509,7 +417,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 = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paints..circle(x: 50, y: 50, color: splashColor)); await gesture.up(); focusNode.dispose(); @@ -538,7 +446,7 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderObject inkFeatures = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 0)); focusNode.requestFocus(); await tester.pumpAndSettle(); @@ -569,7 +477,7 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderObject inkFeatures = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0)); focusNode.requestFocus(); @@ -605,7 +513,7 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderObject inkFeatures = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0)); // Hover the ink well. @@ -647,7 +555,7 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderObject inkFeatures = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 0)); expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0)); @@ -699,7 +607,7 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderObject inkFeatures = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 0)); expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0)); @@ -752,7 +660,7 @@ testWidgets('InkResponse radius can be updated', (WidgetTester tester) async { } await tester.pumpWidget(boilerplate(10)); await tester.pumpAndSettle(); - final RenderObject inkFeatures = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 0)); focusNode.requestFocus(); @@ -793,7 +701,7 @@ testWidgets('InkResponse radius can be updated', (WidgetTester tester) async { await tester.pumpWidget(boilerplate(BoxShape.circle)); await tester.pumpAndSettle(); - final RenderObject inkFeatures = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 0)); expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0)); @@ -834,7 +742,7 @@ testWidgets('InkResponse radius can be updated', (WidgetTester tester) async { await tester.pumpWidget(boilerplate(BorderRadius.circular(10))); await tester.pumpAndSettle(); - final RenderObject inkFeatures = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0)); focusNode.requestFocus(); @@ -883,7 +791,7 @@ testWidgets('InkResponse radius can be updated', (WidgetTester tester) async { await tester.pumpWidget(boilerplate(BorderRadius.circular(20))); await tester.pumpAndSettle(); - final RenderObject inkFeatures = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 0)); focusNode.requestFocus(); @@ -954,7 +862,7 @@ testWidgets('InkResponse radius can be updated', (WidgetTester tester) async { await tester.pumpWidget(boilerplate(BorderRadius.circular(20))); await tester.pumpAndSettle(); - final RenderObject inkFeatures = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 0)); final TestGesture gesture = await tester.startGesture(tester.getRect(find.byType(InkWell)).center); @@ -1037,7 +945,7 @@ testWidgets('InkResponse radius can be updated', (WidgetTester tester) async { ), )); await tester.pumpAndSettle(); - final RenderObject inkFeatures = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paintsExactlyCountTimes(#drawRect, 0)); focusNode.requestFocus(); await tester.pumpAndSettle(); @@ -2140,7 +2048,7 @@ testWidgets('InkResponse radius can be updated', (WidgetTester tester) async { expect(log, equals(['tap-down', 'double-tap'])); await tester.pumpAndSettle(); - final RenderObject inkFeatures = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paintsExactlyCountTimes(#drawRect, 0)); }); @@ -2185,7 +2093,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 = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 0)); }); @@ -2263,7 +2171,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 = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); // 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 @@ -2328,7 +2236,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 = getInkFeatures(tester); + final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 0)); await gesture.up(); From 81fad61209cbb38724a1201665f79fce6364f0a0 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Thu, 28 Nov 2024 11:14:14 -0500 Subject: [PATCH 241/386] Roll Packages from e6932b77a183 to bc0c22d57910 (2 revisions) (#159592) https://github.com/flutter/packages/compare/e6932b77a183...bc0c22d57910 2024-11-27 34871572+gmackall@users.noreply.github.com [image_picker_android] Refactor interactions with ContentProvider provided filenames (flutter/packages#8188) 2024-11-27 34871572+gmackall@users.noreply.github.com [file_selector_android] Refactor interactions with `ContentProvider` provided filenames (flutter/packages#8184) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-packages-flutter-autoroll Please CC flutter-ecosystem@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/flutter_packages.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/flutter_packages.version b/bin/internal/flutter_packages.version index f6d4b7f01e7..b515ddb28da 100644 --- a/bin/internal/flutter_packages.version +++ b/bin/internal/flutter_packages.version @@ -1 +1 @@ -e6932b77a183661e19136993094c3cc268900562 +bc0c22d57910047fff7569ccb4413cf031304c7d From bc0b62a2ab6c02e91f84f9b4b4cedeeacba89146 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Thu, 28 Nov 2024 14:23:25 -0500 Subject: [PATCH 242/386] Roll Flutter Engine from d7c0bcfe7a30 to d7be573a5ee5 (1 revision) (#159595) https://github.com/flutter/engine/compare/d7c0bcfe7a30...d7be573a5ee5 2024-11-28 chris@bracken.jp iOS: Apply nullability annotations to FlutterPlatformViewsController (flutter/engine#56839) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index cc185f3044e..ac4249066cb 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -d7c0bcfe7a30408b0722c9d47d8b0b1e4cdb9c81 +d7be573a5ee5e1ff7b5cf003185a06d6faf87f46 From a0ba2decab156c88708c4261d40660ab8f60da5f Mon Sep 17 00:00:00 2001 From: PurplePolyhedron <120297255+PurplePolyhedron@users.noreply.github.com> Date: Fri, 29 Nov 2024 18:20:31 +1000 Subject: [PATCH 243/386] improve `ContainerRenderObjectMixin` error message when `parentData` is not set up properly (#157846) Previously when subclassing `MultiChildRenderObjectWidget` and `RenderObject with ContainerRenderObjectMixin`, if one forgot to set up parent data, the error message does not give hint that `setupParentData` need to be implemented by the `RenderObject`. This PR add assertion that check parent data type before type cast and give hints if it is was not properly set. ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- .../flutter/lib/src/rendering/object.dart | 6 ++++ .../flutter/test/rendering/object_test.dart | 29 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/packages/flutter/lib/src/rendering/object.dart b/packages/flutter/lib/src/rendering/object.dart index 1c3b3c051ed..9c0df3882c4 100644 --- a/packages/flutter/lib/src/rendering/object.dart +++ b/packages/flutter/lib/src/rendering/object.dart @@ -4353,6 +4353,12 @@ mixin ContainerRenderObjectMixin 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 +504,16 @@ class TestRenderObject extends RenderObject with ContainerRenderObjectMixin Date: Mon, 2 Dec 2024 12:03:20 -0500 Subject: [PATCH 244/386] Roll Flutter Engine from d7be573a5ee5 to 1f6312df6d75 (1 revision) (#159676) https://github.com/flutter/engine/compare/d7be573a5ee5...1f6312df6d75 2024-11-29 skia-flutter-autoroll@skia.org Roll Fuchsia Linux SDK from oJzuSXcrUmaw5Ck2g... to pc49rc4B22IXqigQ-... (flutter/engine#56876) Also rolling transitive DEPS: fuchsia/sdk/core/linux-amd64 from oJzuSXcrUmaw to pc49rc4B22IX If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-engine-flutter-autoroll Please CC zra@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- bin/internal/engine.version | 2 +- bin/internal/fuchsia-linux.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index ac4249066cb..7c9f0b46ab5 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -d7be573a5ee5e1ff7b5cf003185a06d6faf87f46 +1f6312df6d75cdfc72f47cc79acf8d2adb86c922 diff --git a/bin/internal/fuchsia-linux.version b/bin/internal/fuchsia-linux.version index be859fd9c6a..c48130635df 100644 --- a/bin/internal/fuchsia-linux.version +++ b/bin/internal/fuchsia-linux.version @@ -1 +1 @@ -oJzuSXcrUmaw5Ck2gZW7hP5H95_HPDVv4fRSDD5ASfMC +pc49rc4B22IXqigQ-47f6b2BmQwUuSIMPQxP9N-ybj0C From e7a8dc3a2780d3b7f7eae8d97d33da5aacfb8528 Mon Sep 17 00:00:00 2001 From: Justin McCandless Date: Mon, 2 Dec 2024 09:45:36 -0800 Subject: [PATCH 245/386] iPad Scribble flicker and crash (#159508) Previously, dragging to select with an Apple Pencil on an iPad (Scribble) caused the context menu to rapidly hide and show. Sometimes this even caused an assertion error when using SystemContextMenu due to showing two context menus in one frame. After this PR, the flicker and crash are gone. The flicker happened on both the Flutter-rendered context menu and SystemContextMenu, but the error only happened with SystemContextMenu due to a safeguard that prevents two from showing at the same time. The flickering is likely a regression caused by https://github.com/flutter/flutter/pull/142463. | Before this PR | After this PR | | --- | --- | |