diff --git a/.ci.yaml b/.ci.yaml index 6d473a55e8a..3e985cec680 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -2274,7 +2274,7 @@ targets: - name: Linux web_tool_tests recipe: flutter/flutter_drone - timeout: 90 # https://github.com/flutter/flutter/issues/169634 + timeout: 60 properties: dependencies: >- [ @@ -2287,7 +2287,7 @@ targets: subshard: "1_1" tags: > ["framework", "hostonly", "shard", "linux"] - test_timeout_secs: "5400" # https://github.com/flutter/flutter/issues/162714 + test_timeout_secs: "3600" # 60 minutes to match the global `timeout` property. runIf: - dev/** - packages/flutter_tools/** @@ -6686,6 +6686,7 @@ targets: subshard: "2_2" tags: > ["framework", "hostonly", "shard"] + test_timeout_secs: "3600" # 60 minutes to match the global `timeout` property. runIf: - dev/** - packages/flutter_tools/** diff --git a/DEPS b/DEPS index 198d80926b6..309c181fc29 100644 --- a/DEPS +++ b/DEPS @@ -14,7 +14,7 @@ vars = { 'flutter_git': 'https://flutter.googlesource.com', 'skia_git': 'https://skia.googlesource.com', 'llvm_git': 'https://llvm.googlesource.com', - 'skia_revision': 'bb3b6bd4be0dd757165a5723e1794f7ad2211d49', + 'skia_revision': 'c44a36470d077020b978f87fc5720f85dfc68d5b', # WARNING: DO NOT EDIT canvaskit_cipd_instance MANUALLY # See `lib/web_ui/README.md` for how to roll CanvasKit to a new version. @@ -56,7 +56,7 @@ vars = { # Dart is: https://github.com/dart-lang/sdk/blob/main/DEPS # You can use //tools/dart/create_updated_flutter_deps.py to produce # updated revision list of existing dependencies. - 'dart_revision': 'af31d2637b6bced76edd4bcead0d941fe9ad871a', + 'dart_revision': '8ffec1435cf31802e237765d6e9aae48fe5bd19e', # WARNING: DO NOT EDIT MANUALLY # The lines between blank lines above and below are generated by a script. See create_updated_flutter_deps.py @@ -71,10 +71,10 @@ vars = { 'dart_libprotobuf_rev': '24487dd1045c7f3d64a21f38a3f0c06cc4cf2edb', 'dart_perfetto_rev': '13ce0c9e13b0940d2476cd0cff2301708a9a2e2b', 'dart_protobuf_gn_rev': 'ca669f79945418f6229e4fef89b666b2a88cbb10', - 'dart_protobuf_rev': '07eed6e8cc0535189112ae8373aa8f16f4a5c3ca', - 'dart_pub_rev': '469eb6193c0a49495ea2ce7432cf749f077ad596', + 'dart_protobuf_rev': '14bbd0bd7ff9b7e322ff4e85bd243f6905170b92', + 'dart_pub_rev': 'f7f1891e2de3d795532f45ec214f88ac912ffcd6', 'dart_sync_http_rev': '6666fff944221891182e1f80bf56569338164d72', - 'dart_tools_rev': 'ecd7dd523c8a5761f337eedce8878b092996a75c', + 'dart_tools_rev': '2ef298e48450de9d2443d466ec4d61172a71b113', 'dart_vector_math_rev': '3939545edc38ed657381381d33acde02c49ff827', 'dart_web_rev': '0baaea4de4dfd60db85dd112d8cc7480d0dd8bd8', 'dart_webdev_rev': '23aefebea46c1f94c27703743b2c8db1f651bf29', @@ -368,7 +368,7 @@ deps = { Var('dart_git') + '/external/github.com/google/webkit_inspection_protocol.dart.git' + '@' + Var('dart_webkit_inspection_protocol_rev'), 'engine/src/flutter/third_party/dart/tools/sdks/dart-sdk': - {'dep_type': 'cipd', 'packages': [{'package': 'dart/dart-sdk/${{platform}}', 'version': 'git_revision:0bf5d0bb49d7872a1a01e55dbea63ad7455d754e'}]}, + {'dep_type': 'cipd', 'packages': [{'package': 'dart/dart-sdk/${{platform}}', 'version': 'git_revision:782552bdddc112c62db28ec7e9b2763f4457a3ea'}]}, # WARNING: end of dart dependencies list that is cleaned up automatically - see create_updated_flutter_deps.py. @@ -807,7 +807,7 @@ deps = { 'packages': [ { 'package': 'fuchsia/sdk/core/linux-amd64', - 'version': 'rcOl0yxJb4znJ903YZ0BtnELs13r0WQ7TACeefPZ3bgC' + 'version': '1Ai6VL4vb_GdGnWhg0uhlZW3yT8DJinUL0G7BZ_yGcIC' } ], 'condition': 'download_fuchsia_deps and not download_fuchsia_sdk', diff --git a/bin/internal/flutter_packages.version b/bin/internal/flutter_packages.version index 2c24c07b9cf..fae1bdd6a54 100644 --- a/bin/internal/flutter_packages.version +++ b/bin/internal/flutter_packages.version @@ -1 +1 @@ -34eec7850cce13f0b60f041ca6cea1206abd957e +287739d0accebbcd6459dfa86f559916db793318 diff --git a/dev/devicelab/bin/tasks/module_uiscene_test_ios.dart b/dev/devicelab/bin/tasks/module_uiscene_test_ios.dart index e212b1c0a00..995d65d804a 100644 --- a/dev/devicelab/bin/tasks/module_uiscene_test_ios.dart +++ b/dev/devicelab/bin/tasks/module_uiscene_test_ios.dart @@ -213,11 +213,14 @@ Future _installPlugins({ await eval( 'pod', - ['install'], - environment: {'LANG': 'en_US.UTF-8'}, + ['install', '--verbose'], + environment: { + // See https://github.com/flutter/flutter/issues/10873. + // CocoaPods analytics adds a lot of latency. + 'COCOAPODS_DISABLE_STATS': 'true', + 'LANG': 'en_US.UTF-8', + }, workingDirectory: xcodeProjectDir.path, - printStdout: false, - printStderr: false, ); } diff --git a/engine/src/flutter/ci/builders/linux_web_engine_test.json b/engine/src/flutter/ci/builders/linux_web_engine_test.json index 57d464dbf6a..62655908564 100644 --- a/engine/src/flutter/ci/builders/linux_web_engine_test.json +++ b/engine/src/flutter/ci/builders/linux_web_engine_test.json @@ -328,7 +328,7 @@ }, { "dependency": "firefox", - "version": "version:132.0" + "version": "version:143.0" } ], "tasks": [ diff --git a/engine/src/flutter/lib/ui/dart_ui.cc b/engine/src/flutter/lib/ui/dart_ui.cc index 44c21df9901..9b5921d58cb 100644 --- a/engine/src/flutter/lib/ui/dart_ui.cc +++ b/engine/src/flutter/lib/ui/dart_ui.cc @@ -101,6 +101,7 @@ typedef CanvasPath Path; V(PlatformConfigurationNativeApi::EndWarmUpFrame) \ V(PlatformConfigurationNativeApi::Render) \ V(PlatformConfigurationNativeApi::UpdateSemantics) \ + V(PlatformConfigurationNativeApi::SetApplicationLocale) \ V(PlatformConfigurationNativeApi::SetNeedsReportTimings) \ V(PlatformConfigurationNativeApi::SetIsolateDebugName) \ V(PlatformConfigurationNativeApi::SetSemanticsTreeEnabled) \ diff --git a/engine/src/flutter/lib/ui/platform_dispatcher.dart b/engine/src/flutter/lib/ui/platform_dispatcher.dart index ff5a56e0b4e..a799001c010 100644 --- a/engine/src/flutter/lib/ui/platform_dispatcher.dart +++ b/engine/src/flutter/lib/ui/platform_dispatcher.dart @@ -976,6 +976,15 @@ class PlatformDispatcher { /// list has not been set or is empty. Locale get locale => locales.isEmpty ? const Locale.fromSubtags() : locales.first; + /// Sets the locale for the application in engine. + /// + /// This is typically called by framework to set the locale based on which + /// locale the Flutter app actually uses. + void setApplicationLocale(Locale locale) => _setApplicationLocale(locale.toLanguageTag()); + + @Native(symbol: 'PlatformConfigurationNativeApi::SetApplicationLocale') + external static void _setApplicationLocale(String locale); + /// The full system-reported supported locales of the device. /// /// This establishes the language and formatting conventions that application diff --git a/engine/src/flutter/lib/ui/semantics/semantics_node.h b/engine/src/flutter/lib/ui/semantics/semantics_node.h index d419b3e037f..7ca763f3078 100644 --- a/engine/src/flutter/lib/ui/semantics/semantics_node.h +++ b/engine/src/flutter/lib/ui/semantics/semantics_node.h @@ -168,6 +168,7 @@ struct SemanticsNode { std::string linkUrl; SemanticsRole role; SemanticsValidationResult validationResult = SemanticsValidationResult::kNone; + // A locale string in BCP 47 format std::string locale; }; diff --git a/engine/src/flutter/lib/ui/window/platform_configuration.cc b/engine/src/flutter/lib/ui/window/platform_configuration.cc index 2edeb2cf598..9c63ebc1501 100644 --- a/engine/src/flutter/lib/ui/window/platform_configuration.cc +++ b/engine/src/flutter/lib/ui/window/platform_configuration.cc @@ -677,6 +677,14 @@ void PlatformConfigurationNativeApi::UpdateSemantics(int64_t view_id, view_id, update); } +void PlatformConfigurationNativeApi::SetApplicationLocale(std::string locale) { + UIDartState::ThrowIfUIOperationsProhibited(); + UIDartState::Current() + ->platform_configuration() + ->client() + ->SetApplicationLocale(std::move(locale)); +} + void PlatformConfigurationNativeApi::SetSemanticsTreeEnabled(bool enabled) { UIDartState::ThrowIfUIOperationsProhibited(); UIDartState::Current() diff --git a/engine/src/flutter/lib/ui/window/platform_configuration.h b/engine/src/flutter/lib/ui/window/platform_configuration.h index 0f307329234..c1a489d059f 100644 --- a/engine/src/flutter/lib/ui/window/platform_configuration.h +++ b/engine/src/flutter/lib/ui/window/platform_configuration.h @@ -98,6 +98,13 @@ class PlatformConfigurationClient { /// virtual void UpdateSemantics(int64_t viewId, SemanticsUpdate* update) = 0; + //-------------------------------------------------------------------------- + /// @brief Framework sets the application locale + /// + /// @param[in] locale The application locale in BCP 47 format. + /// + virtual void SetApplicationLocale(std::string locale) = 0; + //-------------------------------------------------------------------------- /// @brief Notifies whether Framework starts generating semantics tree. /// @@ -633,6 +640,8 @@ class PlatformConfigurationNativeApi { static void UpdateSemantics(int64_t viewId, SemanticsUpdate* update); + static void SetApplicationLocale(std::string locale); + static void SetSemanticsTreeEnabled(bool enabled); static void SetNeedsReportTimings(bool value); diff --git a/engine/src/flutter/lib/web_ui/README.md b/engine/src/flutter/lib/web_ui/README.md index b7da699abe1..aed41d42542 100644 --- a/engine/src/flutter/lib/web_ui/README.md +++ b/engine/src/flutter/lib/web_ui/README.md @@ -195,20 +195,17 @@ If you have questions, contact the Flutter Web team on Flutter Discord on the We test with Firefox on LUCI in the Linux Web Engine builder. The process for rolling Firefox is even easier than Chromium. Simply update `package_lock.yaml` -with the latest version of Firefox, and run `package_roller.dart`. +with the latest version of Firefox, and run: +``` +dart dev/package_roller.dart +``` #### .ci.yaml -After rolling Chrome and/or Firefox, also update the CI dependencies in -`.ci.yaml` to make use of the new versions. The lines look like +After rolling Chrome and/or Firefox, also update the CI dependencies by running: -```yaml - dependencies: >- - [ - {"dependency": "chrome_and_driver", "version": "version:107.0"}, - {"dependency": "firefox", "version": "version:83.0"}, - {"dependency": "goldctl", "version": "git_revision:720a542f6fe4f92922c3b8f0fdcc4d2ac6bb83cd"} - ] +``` +felt generate-builder-json ``` ##### **package_roller.dart** diff --git a/engine/src/flutter/lib/web_ui/dev/common.dart b/engine/src/flutter/lib/web_ui/dev/common.dart index 4a4af8f414b..b8e9d10d4a9 100644 --- a/engine/src/flutter/lib/web_ui/dev/common.dart +++ b/engine/src/flutter/lib/web_ui/dev/common.dart @@ -75,7 +75,7 @@ class WindowsPlatformBinding extends PlatformBinding { @override String getFirefoxDownloadUrl(String version) => - 'https://download-installer.cdn.mozilla.net/pub/firefox/releases/$version/win64/en-US/' + 'https://ftp.mozilla.org/pub/firefox/releases/$version/win64/en-US/' '${getFirefoxDownloadFilename(version)}'; @override @@ -109,11 +109,11 @@ class LinuxPlatformBinding extends PlatformBinding { @override String getFirefoxDownloadUrl(String version) => - 'https://download-installer.cdn.mozilla.net/pub/firefox/releases/$version/linux-x86_64/en-US/' + 'https://ftp.mozilla.org/pub/firefox/releases/$version/linux-x86_64/en-US/' '${getFirefoxDownloadFilename(version)}'; @override - String getFirefoxDownloadFilename(String version) => 'firefox-$version.tar.bz2'; + String getFirefoxDownloadFilename(String version) => 'firefox-$version.tar.xz'; @override String getFirefoxExecutablePath(io.Directory versionDir) => @@ -145,7 +145,7 @@ abstract class MacPlatformBinding extends PlatformBinding { @override String getFirefoxDownloadUrl(String version) => - 'https://download-installer.cdn.mozilla.net/pub/firefox/releases/$version/mac/en-US/' + 'https://ftp.mozilla.org/pub/firefox/releases/$version/mac/en-US/' '${getFirefoxDownloadFilename(version)}'; @override diff --git a/engine/src/flutter/lib/web_ui/dev/package_lock.yaml b/engine/src/flutter/lib/web_ui/dev/package_lock.yaml index 5a04c2d6591..84a5584e471 100644 --- a/engine/src/flutter/lib/web_ui/dev/package_lock.yaml +++ b/engine/src/flutter/lib/web_ui/dev/package_lock.yaml @@ -4,7 +4,7 @@ chrome: version: '133.0.6943.53' firefox: - version: '132.0' + version: '143.0' edge: launcher_version: '1.2.0.0' diff --git a/engine/src/flutter/lib/web_ui/lib/platform_dispatcher.dart b/engine/src/flutter/lib/web_ui/lib/platform_dispatcher.dart index 36b74594828..4ef10f8afc6 100644 --- a/engine/src/flutter/lib/web_ui/lib/platform_dispatcher.dart +++ b/engine/src/flutter/lib/web_ui/lib/platform_dispatcher.dart @@ -87,6 +87,8 @@ abstract class PlatformDispatcher { void setSemanticsTreeEnabled(bool enabled) {} + void setApplicationLocale(Locale locale) {} + AccessibilityFeatures get accessibilityFeatures; VoidCallback? get onAccessibilityFeaturesChanged; diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/text_field.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/text_field.dart index 59567e10fee..e86283c0911 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/text_field.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/text_field.dart @@ -353,13 +353,28 @@ class SemanticTextField extends SemanticRole { if (semanticsObject.flags.isObscured) { input.type = 'password'; } else { - input.type = switch (semanticsObject.inputType) { - ui.SemanticsInputType.search => 'search', - ui.SemanticsInputType.email => 'email', - ui.SemanticsInputType.url => 'url', - ui.SemanticsInputType.phone => 'tel', - _ => 'text', - }; + // For email inputs, prefer type="text" with inputmode="email" so that + // browsers keep selection APIs enabled while still providing email + // keyboards and hints. This avoids InvalidStateError and enables + // proper selection/cursor operations. + input.removeAttribute('inputmode'); + input.removeAttribute('autocapitalize'); + input.autocomplete = 'off'; + input.type = 'text'; + + switch (semanticsObject.inputType) { + case ui.SemanticsInputType.search: + input.type = 'search'; + case ui.SemanticsInputType.url: + input.type = 'url'; + case ui.SemanticsInputType.phone: + input.type = 'tel'; + case ui.SemanticsInputType.email: + input.setAttribute('inputmode', 'email'); + input.setAttribute('autocapitalize', 'none'); + input.autocomplete = 'email'; + default: + } } } diff --git a/engine/src/flutter/lib/web_ui/test/engine/semantics/text_field_test.dart b/engine/src/flutter/lib/web_ui/test/engine/semantics/text_field_test.dart index e0dc95eafff..01df1f9ef36 100644 --- a/engine/src/flutter/lib/web_ui/test/engine/semantics/text_field_test.dart +++ b/engine/src/flutter/lib/web_ui/test/engine/semantics/text_field_test.dart @@ -124,7 +124,8 @@ void testMain() { ui.SemanticsInputType.url: 'url', ui.SemanticsInputType.phone: 'tel', ui.SemanticsInputType.search: 'search', - ui.SemanticsInputType.email: 'email', + // Email uses type="text" to preserve selection APIs under semantics. + ui.SemanticsInputType.email: 'text', }; for (final ui.SemanticsInputType type in ui.SemanticsInputType.values) { createTextFieldSemantics(value: 'text', inputType: type); @@ -133,6 +134,19 @@ void testMain() { } }); + test('email input uses type=text with inputmode=email and autocomplete=email', () { + createTextFieldSemantics(value: 'text', inputType: ui.SemanticsInputType.email); + + final node = owner().debugSemanticsTree![0]!; + final textFieldRole = node.semanticRole! as SemanticTextField; + final inputElement = textFieldRole.editableElement as DomHTMLInputElement; + + expect(inputElement.type, 'text'); + expect(inputElement.getAttribute('inputmode'), 'email'); + expect(inputElement.getAttribute('autocapitalize'), 'none'); + expect(inputElement.autocomplete, 'email'); + }); + test('renders a disabled text field', () { createTextFieldSemantics(isEnabled: false, value: 'hello'); expectSemanticsTree(owner(), ''''''); diff --git a/engine/src/flutter/runtime/dart_isolate_unittests.cc b/engine/src/flutter/runtime/dart_isolate_unittests.cc index 3be980588e1..e39dd4a2699 100644 --- a/engine/src/flutter/runtime/dart_isolate_unittests.cc +++ b/engine/src/flutter/runtime/dart_isolate_unittests.cc @@ -712,6 +712,7 @@ class FakePlatformConfigurationClient : public PlatformConfigurationClient { double width, double height) override {} void UpdateSemantics(int64_t view_id, SemanticsUpdate* update) override {} + void SetApplicationLocale(std::string locale) override {} void SetSemanticsTreeEnabled(bool enabled) override {} void HandlePlatformMessage( std::unique_ptr message) override {} diff --git a/engine/src/flutter/runtime/runtime_controller.cc b/engine/src/flutter/runtime/runtime_controller.cc index 95708ef3585..53f1684eea6 100644 --- a/engine/src/flutter/runtime/runtime_controller.cc +++ b/engine/src/flutter/runtime/runtime_controller.cc @@ -444,6 +444,11 @@ void RuntimeController::UpdateSemantics(int64_t view_id, client_.UpdateSemantics(view_id, update->takeNodes(), update->takeActions()); } +// |PlatformConfigurationClient| +void RuntimeController::SetApplicationLocale(std::string locale) { + client_.SetApplicationLocale(std::move(locale)); +} + // |PlatformConfigurationClient| void RuntimeController::SetSemanticsTreeEnabled(bool enabled) { client_.SetSemanticsTreeEnabled(enabled); diff --git a/engine/src/flutter/runtime/runtime_controller.h b/engine/src/flutter/runtime/runtime_controller.h index 1c7df47280f..38a279bf3f5 100644 --- a/engine/src/flutter/runtime/runtime_controller.h +++ b/engine/src/flutter/runtime/runtime_controller.h @@ -636,6 +636,9 @@ class RuntimeController : public PlatformConfigurationClient, // |PlatformConfigurationClient| void UpdateSemantics(int64_t view_id, SemanticsUpdate* update) override; + // |PlatformConfigurationClient| + void SetApplicationLocale(std::string locale) override; + // |PlatformConfigurationClient| void SetSemanticsTreeEnabled(bool enabled) override; diff --git a/engine/src/flutter/runtime/runtime_controller_unittests.cc b/engine/src/flutter/runtime/runtime_controller_unittests.cc index a8e27bae1e3..08d0b3ecc7e 100644 --- a/engine/src/flutter/runtime/runtime_controller_unittests.cc +++ b/engine/src/flutter/runtime/runtime_controller_unittests.cc @@ -19,6 +19,7 @@ class MockRuntimeDelegate : public RuntimeDelegate { std::vector updates; std::vector actions; std::string DefaultRouteName() override { return ""; } + std::string locale; void ScheduleFrame(bool regenerate_layer_trees = true) override {} @@ -35,6 +36,10 @@ class MockRuntimeDelegate : public RuntimeDelegate { this->actions.push_back(actions); } + void SetApplicationLocale(std::string locale) override { + this->locale = std::move(locale); + } + void SetSemanticsTreeEnabled(bool enabled) override {} void HandlePlatformMessage( @@ -96,6 +101,12 @@ class RuntimeControllerTester { ASSERT_FALSE(delegate_.actions.empty()); } + void CanUpdateSetApplicationLocale() { + ASSERT_TRUE(delegate_.locale.empty()); + runtime_controller_.SetApplicationLocale("es-MX"); + ASSERT_TRUE(delegate_.locale == "es-MX"); + } + private: MockRuntimeDelegate delegate_; UIDartState::Context& context_; @@ -146,4 +157,16 @@ TEST_F(RuntimeControllerTest, CanUpdateSemanticsWhenSetSemanticsTreeEnabled) { DestroyShell(std::move(shell), task_runners); } +TEST_F(RuntimeControllerTest, CanSetApplicationLocale) { + TaskRunners task_runners("test", // label + GetCurrentTaskRunner(), // platform + CreateNewThread(), // raster + CreateNewThread(), // ui + CreateNewThread() // io + ); + UIDartState::Context context(task_runners); + auto tester = std::make_shared(context); + tester->CanUpdateSetApplicationLocale(); +} + } // namespace flutter::testing diff --git a/engine/src/flutter/runtime/runtime_delegate.h b/engine/src/flutter/runtime/runtime_delegate.h index 84ca390db09..3563cd5f887 100644 --- a/engine/src/flutter/runtime/runtime_delegate.h +++ b/engine/src/flutter/runtime/runtime_delegate.h @@ -36,6 +36,8 @@ class RuntimeDelegate { SemanticsNodeUpdates update, CustomAccessibilityActionUpdates actions) = 0; + virtual void SetApplicationLocale(std::string locale) = 0; + virtual void SetSemanticsTreeEnabled(bool enabled) = 0; virtual void HandlePlatformMessage( diff --git a/engine/src/flutter/shell/common/engine.cc b/engine/src/flutter/shell/common/engine.cc index 1848b9db53f..bce7fa5007d 100644 --- a/engine/src/flutter/shell/common/engine.cc +++ b/engine/src/flutter/shell/common/engine.cc @@ -529,6 +529,10 @@ void Engine::UpdateSemantics(int64_t view_id, std::move(actions)); } +void Engine::SetApplicationLocale(std::string locale) { + delegate_.OnEngineSetApplicationLocale(std::move(locale)); +} + void Engine::SetSemanticsTreeEnabled(bool enabled) { delegate_.OnEngineSetSemanticsTreeEnabled(enabled); } diff --git a/engine/src/flutter/shell/common/engine.h b/engine/src/flutter/shell/common/engine.h index bee80938fdf..e07f7d4f569 100644 --- a/engine/src/flutter/shell/common/engine.h +++ b/engine/src/flutter/shell/common/engine.h @@ -161,6 +161,13 @@ class Engine final : public RuntimeDelegate, PointerDataDispatcher::Delegate { SemanticsNodeUpdates updates, CustomAccessibilityActionUpdates actions) = 0; + //-------------------------------------------------------------------------- + /// @brief Framework sets the application locale. + /// + /// @param[in] locale The application locale in BCP 47 format. + /// + virtual void OnEngineSetApplicationLocale(std::string locale) = 0; + //-------------------------------------------------------------------------- /// @brief When the Framework starts or stops generating semantics /// tree, @@ -1029,6 +1036,9 @@ class Engine final : public RuntimeDelegate, PointerDataDispatcher::Delegate { SemanticsNodeUpdates update, CustomAccessibilityActionUpdates actions) override; + // |RuntimeDelegate| + void SetApplicationLocale(std::string locale) override; + // |RuntimeDelegate| void SetSemanticsTreeEnabled(bool enabled) override; diff --git a/engine/src/flutter/shell/common/engine_animator_unittests.cc b/engine/src/flutter/shell/common/engine_animator_unittests.cc index f1010131615..f7653b89541 100644 --- a/engine/src/flutter/shell/common/engine_animator_unittests.cc +++ b/engine/src/flutter/shell/common/engine_animator_unittests.cc @@ -57,6 +57,10 @@ class MockDelegate : public Engine::Delegate { OnEngineUpdateSemantics, (int64_t, SemanticsNodeUpdates, CustomAccessibilityActionUpdates), (override)); + MOCK_METHOD(void, + OnEngineSetApplicationLocale, + (const std::string), + (override)); MOCK_METHOD(void, OnEngineSetSemanticsTreeEnabled, (bool), (override)); MOCK_METHOD(void, OnEngineHandlePlatformMessage, diff --git a/engine/src/flutter/shell/common/engine_unittests.cc b/engine/src/flutter/shell/common/engine_unittests.cc index 324104d9185..3c4673f801e 100644 --- a/engine/src/flutter/shell/common/engine_unittests.cc +++ b/engine/src/flutter/shell/common/engine_unittests.cc @@ -64,6 +64,10 @@ class MockDelegate : public Engine::Delegate { OnEngineUpdateSemantics, (int64_t, SemanticsNodeUpdates, CustomAccessibilityActionUpdates), (override)); + MOCK_METHOD(void, + OnEngineSetApplicationLocale, + (const std::string), + (override)); MOCK_METHOD(void, OnEngineSetSemanticsTreeEnabled, (bool), (override)); MOCK_METHOD(void, OnEngineHandlePlatformMessage, @@ -116,6 +120,7 @@ class MockRuntimeDelegate : public RuntimeDelegate { UpdateSemantics, (int64_t, SemanticsNodeUpdates, CustomAccessibilityActionUpdates), (override)); + MOCK_METHOD(void, SetApplicationLocale, (const std::string), (override)); MOCK_METHOD(void, SetSemanticsTreeEnabled, (bool), (override)); MOCK_METHOD(void, HandlePlatformMessage, diff --git a/engine/src/flutter/shell/common/platform_view.cc b/engine/src/flutter/shell/common/platform_view.cc index 496c75f85d2..462acd516a8 100644 --- a/engine/src/flutter/shell/common/platform_view.cc +++ b/engine/src/flutter/shell/common/platform_view.cc @@ -130,6 +130,10 @@ void PlatformView::UpdateSemantics( // NOLINTNEXTLINE(performance-unnecessary-value-param) CustomAccessibilityActionUpdates actions) {} +void PlatformView::SetApplicationLocale( + std::string locale // NOLINT(performance-unnecessary-value-param) +) {} + void PlatformView::SetSemanticsTreeEnabled( bool enabled // NOLINT(performance-unnecessary-value-param) ) {} diff --git a/engine/src/flutter/shell/common/platform_view.h b/engine/src/flutter/shell/common/platform_view.h index 9332c76d3ca..60227f386b4 100644 --- a/engine/src/flutter/shell/common/platform_view.h +++ b/engine/src/flutter/shell/common/platform_view.h @@ -514,6 +514,14 @@ class PlatformView { SemanticsNodeUpdates updates, CustomAccessibilityActionUpdates actions); + //---------------------------------------------------------------------------- + /// @brief Used by the framework to set application locale in the + /// embedding + /// + /// @param[in] locale The application locale in BCP 47 format. + /// + virtual void SetApplicationLocale(std::string locale); + //---------------------------------------------------------------------------- /// @brief Used by the framework to tell the embedder to prepare or clear /// resoruce for accepting semantics tree. diff --git a/engine/src/flutter/shell/common/shell.cc b/engine/src/flutter/shell/common/shell.cc index c8e9154a7a5..73d05330599 100644 --- a/engine/src/flutter/shell/common/shell.cc +++ b/engine/src/flutter/shell/common/shell.cc @@ -1448,6 +1448,20 @@ void Shell::OnEngineUpdateSemantics(int64_t view_id, }); } +// |Engine::Delegate| +void Shell::OnEngineSetApplicationLocale(std::string locale) { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); + + task_runners_.GetPlatformTaskRunner()->RunNowOrPostTask( + task_runners_.GetPlatformTaskRunner(), + [view = platform_view_->GetWeakPtr(), locale_holder = std::move(locale)] { + if (view) { + view->SetApplicationLocale(locale_holder); + } + }); +} + // |Engine::Delegate| void Shell::OnEngineSetSemanticsTreeEnabled(bool enabled) { FML_DCHECK(is_set_up_); diff --git a/engine/src/flutter/shell/common/shell.h b/engine/src/flutter/shell/common/shell.h index a98c3a2aaed..7b86a6523a2 100644 --- a/engine/src/flutter/shell/common/shell.h +++ b/engine/src/flutter/shell/common/shell.h @@ -675,6 +675,9 @@ class Shell final : public PlatformView::Delegate, SemanticsNodeUpdates update, CustomAccessibilityActionUpdates actions) override; + // |Engine::Delegate| + void OnEngineSetApplicationLocale(std::string locale) override; + // |Engine::Delegate| void OnEngineSetSemanticsTreeEnabled(bool enabled) override; diff --git a/engine/src/flutter/shell/platform/android/android_shell_holder_unittests.cc b/engine/src/flutter/shell/platform/android/android_shell_holder_unittests.cc index 2b4a5e67e0e..9664cc06cc5 100644 --- a/engine/src/flutter/shell/platform/android/android_shell_holder_unittests.cc +++ b/engine/src/flutter/shell/platform/android/android_shell_holder_unittests.cc @@ -29,6 +29,10 @@ class MockPlatformViewAndroidJNI : public PlatformViewAndroidJNI { std::vector strings, std::vector> string_attribute_args), (override)); + MOCK_METHOD(void, + FlutterViewSetApplicationLocale, + (const std::string locale), + (override)); MOCK_METHOD(void, FlutterViewUpdateCustomAccessibilityActions, (std::vector actions_buffer, diff --git a/engine/src/flutter/shell/platform/android/io/flutter/embedding/engine/FlutterJNI.java b/engine/src/flutter/shell/platform/android/io/flutter/embedding/engine/FlutterJNI.java index 77d7269035f..2f97368b6e3 100644 --- a/engine/src/flutter/shell/platform/android/io/flutter/embedding/engine/FlutterJNI.java +++ b/engine/src/flutter/shell/platform/android/io/flutter/embedding/engine/FlutterJNI.java @@ -803,6 +803,16 @@ public class FlutterJNI { } } + /** Invoked by native to set application locale in Android. */ + @SuppressWarnings("unused") + @UiThread + private void setApplicationLocale(@NonNull String locale) { + ensureRunningOnMainThread(); + if (accessibilityDelegate != null) { + accessibilityDelegate.setLocale(locale); + } + } + /** * Invoked by native to send new custom accessibility events from Flutter to Android. * @@ -1631,6 +1641,13 @@ public class FlutterJNI { @NonNull ByteBuffer buffer, @NonNull String[] strings, @NonNull ByteBuffer[] stringAttributeArgs); + + /** + * Sets the locale for the assistive technologies. + * + *

Must be called on the main thread + */ + void setLocale(@NonNull String locale); } public interface AsyncWaitForVsyncDelegate { diff --git a/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java b/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java index 8c95a68d00b..def3e430b03 100644 --- a/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java +++ b/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java @@ -227,6 +227,16 @@ public class AccessibilityBridge extends AccessibilityNodeProvider { // a bitmask whose values comes from {@link AccessibilityFeature}. private int accessibilityFeatureFlags = 0; + // The default locale for assistive technologies in BCP 47 format. + // + // For example "en-US", "de-DE", "fr-FR". + @Nullable private String defaultLocale; + + @VisibleForTesting + public void setLocale(@NonNull String locale) { + defaultLocale = locale; + } + // The {@code SemanticsNode} within Flutter that currently has the focus of Android's input // system. // @@ -372,6 +382,11 @@ public class AccessibilityBridge extends AccessibilityNodeProvider { } AccessibilityBridge.this.updateSemantics(buffer, strings, stringAttributeArgs); } + + @Override + public void setLocale(String locale) { + AccessibilityBridge.this.setLocale(locale); + } }; // Listener that is notified when accessibility is turned on/off. @@ -2795,6 +2810,21 @@ public class AccessibilityBridge extends AccessibilityNodeProvider { return null; } + /** + * Returns the effective locale for this semantics node after taking app default locale into + * account. + * + *

Can be null if there is no preference. + * + * @return the effective locale. + */ + private @Nullable String getEffectiveLocale() { + if (locale != null && !locale.isEmpty()) { + return locale; + } + return accessibilityBridge.defaultLocale; + } + private void updateRecursively( float[] ancestorTransform, Set visitedObjects, boolean forceUpdate) { visitedObjects.add(this); @@ -2890,7 +2920,7 @@ public class AccessibilityBridge extends AccessibilityNodeProvider { return new AccessibilityStringBuilder() .addString(value) .addAttributes(valueAttributes) - .addLocale(locale) + .addLocale(getEffectiveLocale()) .build(); } @@ -2899,7 +2929,7 @@ public class AccessibilityBridge extends AccessibilityNodeProvider { .addString(label) .addAttributes(labelAttributes) .addUrl(linkUrl) - .addLocale(locale) + .addLocale(getEffectiveLocale()) .build(); } @@ -2907,7 +2937,7 @@ public class AccessibilityBridge extends AccessibilityNodeProvider { return new AccessibilityStringBuilder() .addString(hint) .addAttributes(hintAttributes) - .addLocale(locale) + .addLocale(getEffectiveLocale()) .build(); } diff --git a/engine/src/flutter/shell/platform/android/jni/jni_mock.h b/engine/src/flutter/shell/platform/android/jni/jni_mock.h index 8f9158c97de..17939a68c89 100644 --- a/engine/src/flutter/shell/platform/android/jni/jni_mock.h +++ b/engine/src/flutter/shell/platform/android/jni/jni_mock.h @@ -33,6 +33,10 @@ class JNIMock final : public PlatformViewAndroidJNI { std::vector strings, std::vector> string_attribute_args), (override)); + MOCK_METHOD(void, + FlutterViewSetApplicationLocale, + (std::string locale), + (override)); MOCK_METHOD(void, FlutterViewUpdateCustomAccessibilityActions, diff --git a/engine/src/flutter/shell/platform/android/jni/platform_view_android_jni.h b/engine/src/flutter/shell/platform/android/jni/platform_view_android_jni.h index e952c6127a9..0598507d6cc 100644 --- a/engine/src/flutter/shell/platform/android/jni/platform_view_android_jni.h +++ b/engine/src/flutter/shell/platform/android/jni/platform_view_android_jni.h @@ -63,6 +63,13 @@ class PlatformViewAndroidJNI { std::vector strings, std::vector> string_attribute_args) = 0; + //---------------------------------------------------------------------------- + /// @brief Set application locale to a given language. + /// + /// @note Must be called from the platform thread. + /// + virtual void FlutterViewSetApplicationLocale(std::string locale) = 0; + //---------------------------------------------------------------------------- /// @brief Sends new custom accessibility events. /// diff --git a/engine/src/flutter/shell/platform/android/platform_view_android.cc b/engine/src/flutter/shell/platform/android/platform_view_android.cc index 8ac83e0227c..fc19fbbfc87 100644 --- a/engine/src/flutter/shell/platform/android/platform_view_android.cc +++ b/engine/src/flutter/shell/platform/android/platform_view_android.cc @@ -325,6 +325,11 @@ void PlatformViewAndroid::UpdateSemantics( platform_view_android_delegate_.UpdateSemantics(update, actions); } +// |PlatformView| +void PlatformViewAndroid::SetApplicationLocale(std::string locale) { + jni_facade_->FlutterViewSetApplicationLocale(std::move(locale)); +} + void PlatformViewAndroid::RegisterExternalTexture( int64_t texture_id, const fml::jni::ScopedJavaGlobalRef& surface_texture) { diff --git a/engine/src/flutter/shell/platform/android/platform_view_android.h b/engine/src/flutter/shell/platform/android/platform_view_android.h index 0c21ad651b3..644ee25964c 100644 --- a/engine/src/flutter/shell/platform/android/platform_view_android.h +++ b/engine/src/flutter/shell/platform/android/platform_view_android.h @@ -144,6 +144,9 @@ class PlatformViewAndroid final : public PlatformView { flutter::SemanticsNodeUpdates update, flutter::CustomAccessibilityActionUpdates actions) override; + // |PlatformView| + void SetApplicationLocale(std::string locale) override; + // |PlatformView| void HandlePlatformMessage( std::unique_ptr message) override; diff --git a/engine/src/flutter/shell/platform/android/platform_view_android_jni_impl.cc b/engine/src/flutter/shell/platform/android/platform_view_android_jni_impl.cc index 80dcf7458f3..cb88853bbe2 100644 --- a/engine/src/flutter/shell/platform/android/platform_view_android_jni_impl.cc +++ b/engine/src/flutter/shell/platform/android/platform_view_android_jni_impl.cc @@ -69,6 +69,8 @@ static jfieldID g_jni_shell_holder_field = nullptr; "(ILjava/nio/ByteBuffer;)V") \ V(g_update_semantics_method, updateSemantics, \ "(Ljava/nio/ByteBuffer;[Ljava/lang/String;[Ljava/nio/ByteBuffer;)V") \ + V(g_set_application_locale_method, setApplicationLocale, \ + "(Ljava/lang/String;)V") \ V(g_on_display_platform_view_method, onDisplayPlatformView, \ "(IIIIIIILio/flutter/embedding/engine/mutatorsstack/" \ "FlutterMutatorsStack;)V") \ @@ -1358,6 +1360,24 @@ void PlatformViewAndroidJNIImpl::FlutterViewHandlePlatformMessage( FML_CHECK(fml::jni::CheckException(env)); } +void PlatformViewAndroidJNIImpl::FlutterViewSetApplicationLocale( + std::string locale) { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return; + } + + fml::jni::ScopedJavaLocalRef jlocale = + fml::jni::StringToJavaString(env, locale); + + env->CallVoidMethod(java_object.obj(), g_set_application_locale_method, + jlocale.obj()); + + FML_CHECK(fml::jni::CheckException(env)); +} + void PlatformViewAndroidJNIImpl::FlutterViewHandlePlatformMessageResponse( int responseId, std::unique_ptr data) { diff --git a/engine/src/flutter/shell/platform/android/platform_view_android_jni_impl.h b/engine/src/flutter/shell/platform/android/platform_view_android_jni_impl.h index 06be3d01c1f..bae55e608fb 100644 --- a/engine/src/flutter/shell/platform/android/platform_view_android_jni_impl.h +++ b/engine/src/flutter/shell/platform/android/platform_view_android_jni_impl.h @@ -34,6 +34,8 @@ class PlatformViewAndroidJNIImpl final : public PlatformViewAndroidJNI { std::vector strings, std::vector> string_attribute_args) override; + void FlutterViewSetApplicationLocale(std::string locale) override; + void FlutterViewUpdateCustomAccessibilityActions( std::vector actions_buffer, std::vector strings) override; diff --git a/engine/src/flutter/shell/platform/android/test/io/flutter/view/AccessibilityBridgeTest.java b/engine/src/flutter/shell/platform/android/test/io/flutter/view/AccessibilityBridgeTest.java index 93b5a7997f3..5adc1d11d60 100644 --- a/engine/src/flutter/shell/platform/android/test/io/flutter/view/AccessibilityBridgeTest.java +++ b/engine/src/flutter/shell/platform/android/test/io/flutter/view/AccessibilityBridgeTest.java @@ -885,6 +885,91 @@ public class AccessibilityBridgeTest { assertEquals(actual.getSpanEnd(localeSpan), actual.length()); } + @Test + @Config(minSdk = API_LEVELS.FLUTTER_MIN) + public void itSetsDefaultLocale() { + AccessibilityChannel mockChannel = mock(AccessibilityChannel.class); + AccessibilityViewEmbedder mockViewEmbedder = mock(AccessibilityViewEmbedder.class); + AccessibilityManager mockManager = mock(AccessibilityManager.class); + View mockRootView = mock(View.class); + Context context = mock(Context.class); + when(mockRootView.getContext()).thenReturn(context); + when(context.getPackageName()).thenReturn("test"); + AccessibilityBridge accessibilityBridge = + setUpBridge( + /* rootAccessibilityView= */ mockRootView, + /* accessibilityChannel= */ mockChannel, + /* accessibilityManager= */ mockManager, + /* contentResolver= */ null, + /* accessibilityViewEmbedder= */ mockViewEmbedder, + /* platformViewsAccessibilityDelegate= */ null); + + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + when(mockManager.isEnabled()).thenReturn(true); + + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + root.label = "label"; + + accessibilityBridge.setLocale("es-MX"); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + SpannableString actual = (SpannableString) nodeInfo.getContentDescription(); + assertEquals(actual.toString(), "label"); + Object[] objectSpans = actual.getSpans(0, actual.length(), Object.class); + assertEquals(objectSpans.length, 1); + LocaleSpan localeSpan = (LocaleSpan) objectSpans[0]; + assertEquals(localeSpan.getLocale().toLanguageTag(), "es-MX"); + assertEquals(actual.getSpanStart(localeSpan), 0); + assertEquals(actual.getSpanEnd(localeSpan), actual.length()); + } + + @Test + @Config(minSdk = API_LEVELS.FLUTTER_MIN) + public void itPrioritizesSectionLocale() { + AccessibilityChannel mockChannel = mock(AccessibilityChannel.class); + AccessibilityViewEmbedder mockViewEmbedder = mock(AccessibilityViewEmbedder.class); + AccessibilityManager mockManager = mock(AccessibilityManager.class); + View mockRootView = mock(View.class); + Context context = mock(Context.class); + when(mockRootView.getContext()).thenReturn(context); + when(context.getPackageName()).thenReturn("test"); + AccessibilityBridge accessibilityBridge = + setUpBridge( + /* rootAccessibilityView= */ mockRootView, + /* accessibilityChannel= */ mockChannel, + /* accessibilityManager= */ mockManager, + /* contentResolver= */ null, + /* accessibilityViewEmbedder= */ mockViewEmbedder, + /* platformViewsAccessibilityDelegate= */ null); + + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + when(mockManager.isEnabled()).thenReturn(true); + + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + root.label = "label"; + // Sets both section locale and main locale. + root.locale = "fr-FR"; + accessibilityBridge.setLocale("es-MX"); + + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + SpannableString actual = (SpannableString) nodeInfo.getContentDescription(); + assertEquals(actual.toString(), "label"); + Object[] objectSpans = actual.getSpans(0, actual.length(), Object.class); + assertEquals(objectSpans.length, 1); + LocaleSpan localeSpan = (LocaleSpan) objectSpans[0]; + // Prioritizes section locale over main locale. + assertEquals(localeSpan.getLocale().toLanguageTag(), "fr-FR"); + assertEquals(actual.getSpanStart(localeSpan), 0); + assertEquals(actual.getSpanEnd(localeSpan), actual.length()); + } + @Test @Config(minSdk = API_LEVELS.FLUTTER_MIN) public void itSetsTextCorrectly() { diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h index f22aacb2515..8c61b980e07 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h @@ -48,6 +48,7 @@ typedef void (^FlutterKeyboardAnimationCallback)(fml::TimePoint); @property(nonatomic, readonly) BOOL isPresentingViewController; @property(nonatomic, readonly) BOOL isVoiceOverRunning; @property(nonatomic, strong) FlutterKeyboardManager* keyboardManager; +@property(nonatomic, readwrite) NSString* applicationLocale; /** * @brief Whether the status bar is preferred hidden. diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.mm index b4b344b87fa..73b55e0ed22 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.mm @@ -459,10 +459,10 @@ CGRect ConvertRectToGlobal(SemanticsObject* reference, CGRect local_rect) { return nil; } - if (self.node.locale.empty()) { - return nil; + if (!self.node.locale.empty()) { + return @(self.node.locale.data()); } - return @(self.node.locale.data()); + return self.bridge->GetDefaultLocale(); } - (bool)isFocusable { diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObjectTest.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObjectTest.mm index 225bc799cd6..d6eed6f2650 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObjectTest.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObjectTest.mm @@ -585,6 +585,37 @@ const float kFloatCompareEpsilon = 0.001; XCTAssertTrue([object.accessibilityLanguage isEqualToString:@"es-MX"]); } +- (void)testFlutterSemanticsObjectUseDefaultLocale { + flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge(); + mock->isVoiceOverRunningValue = true; + fml::WeakPtrFactory factory(mock); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + flutter::SemanticsNode node; + mock->mockedLocale = @"es-MX"; + + FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; + [object setSemanticsNode:&node]; + XCTAssertTrue([object.accessibilityLanguage isEqualToString:@"es-MX"]); +} + +- (void)testFlutterSemanticsObjectPrioritizedSectionLocale { + flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge(); + mock->isVoiceOverRunningValue = true; + fml::WeakPtrFactory factory(mock); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + flutter::SemanticsNode node; + // Set both locales. + mock->mockedLocale = @"es-MX"; + node.locale = "zh-TW"; + + FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; + [object setSemanticsNode:&node]; + // node.locale takes priority. + XCTAssertTrue([object.accessibilityLanguage isEqualToString:@"zh-TW"]); +} + - (void)testFlutterSemanticsObjectLocaleNil { flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge(); mock->isVoiceOverRunningValue = true; diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObjectTestMocks.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObjectTestMocks.h index a740349ab13..c64c4cd968c 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObjectTestMocks.h +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObjectTestMocks.h @@ -39,6 +39,8 @@ class MockAccessibilityBridge : public AccessibilityBridgeIos { bool isVoiceOverRunning() const override { return isVoiceOverRunningValue; } UIView* view() const override { return view_; } UIView* textInputView() override { return nil; } + + NSString* GetDefaultLocale() override { return mockedLocale; } void DispatchSemanticsAction(int32_t id, SemanticsAction action) override { SemanticsActionObservation observation(id, action); observations.push_back(observation); @@ -54,6 +56,7 @@ class MockAccessibilityBridge : public AccessibilityBridgeIos { FlutterPlatformViewsController* GetPlatformViewsController() const override { return nil; } std::vector observations; bool isVoiceOverRunningValue; + NSString* mockedLocale; private: UIView* view_; @@ -80,6 +83,7 @@ class MockAccessibilityBridgeNoWindow : public AccessibilityBridgeIos { } void AccessibilityObjectDidBecomeFocused(int32_t id) override {} void AccessibilityObjectDidLoseFocus(int32_t id) override {} + NSString* GetDefaultLocale() override { return nil; } FlutterPlatformViewsController* GetPlatformViewsController() const override { return nil; } std::vector observations; bool isVoiceOverRunningValue; diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h index debad9b257e..1b65d66a998 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h @@ -62,6 +62,7 @@ class AccessibilityBridge final : public AccessibilityBridgeIos { fml::MallocMapping args) override; void AccessibilityObjectDidBecomeFocused(int32_t id) override; void AccessibilityObjectDidLoseFocus(int32_t id) override; + NSString* GetDefaultLocale() override { return view_controller_.applicationLocale; } UIView* textInputView() override; diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_ios.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_ios.h index 2168ca050d0..752e35a4092 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_ios.h +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_ios.h @@ -39,6 +39,7 @@ class AccessibilityBridgeIos { * The input id is the uid of the newly focused SemanticObject. */ virtual void AccessibilityObjectDidLoseFocus(int32_t id) = 0; + virtual NSString* GetDefaultLocale() = 0; virtual FlutterPlatformViewsController* GetPlatformViewsController() const = 0; }; diff --git a/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h b/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h index 7f03b7b8abb..6594bc94f29 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h +++ b/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h @@ -13,6 +13,7 @@ #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" #import "flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h" #import "flutter/shell/platform/darwin/ios/ios_context.h" #import "flutter/shell/platform/darwin/ios/ios_external_view_embedder.h" @@ -110,6 +111,9 @@ class PlatformViewIOS final : public PlatformView { flutter::SemanticsNodeUpdates update, flutter::CustomAccessibilityActionUpdates actions) override; + // |PlatformView| + void SetApplicationLocale(std::string locale) override; + // |PlatformView| std::unique_ptr CreateVSyncWaiter() override; diff --git a/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.mm b/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.mm index b19103eaa28..94b6901cdc9 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.mm @@ -159,6 +159,12 @@ void PlatformViewIOS::UpdateSemantics(int64_t view_id, } } +// |PlatformView| +void PlatformViewIOS::SetApplicationLocale(std::string locale) { + FML_DCHECK(owner_controller_); + owner_controller_.applicationLocale = locale.empty() ? nil : @(locale.data()); +} + // |PlatformView| void PlatformViewIOS::SetSemanticsTreeEnabled(bool enabled) { FML_DCHECK(owner_controller_); diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h index d2d8434ddf3..47d0d8bd6aa 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h @@ -20,6 +20,8 @@ @property(nonatomic, readonly) std::weak_ptr accessibilityBridge; +@property(nonatomic, nullable) NSString* applicationLocale; + /** * Returns YES if provided event is being currently redispatched by keyboard manager. */ diff --git a/engine/src/flutter/tools/cipd/android_embedding_bundle/README.md b/engine/src/flutter/tools/cipd/android_embedding_bundle/README.md index c249d590d4a..f1d99fe2aed 100644 --- a/engine/src/flutter/tools/cipd/android_embedding_bundle/README.md +++ b/engine/src/flutter/tools/cipd/android_embedding_bundle/README.md @@ -5,7 +5,7 @@ contains the build-time dependencies of the Android embedding of the Engine, and the dependencies of the in-tree testing framework. The Android embedder is shipped to Flutter end-users, but these build-time dependencies are not. Therefore, the license script can skip over the destination of the CIPD package -in an Engine checkout at `src/third_party/android_embedding_dependencies`. +in an Engine checkout at `src/flutter/third_party/android_embedding_dependencies`. Even so, the CIPD package should contain a LICENSE file, and the instructions below explain how to fetch the license information for the dependencies. @@ -26,7 +26,7 @@ below explain how to fetch the license information for the dependencies. 1. Examine the file `./build/reports/license/license-dependency.xml`. If it contains licenses other than "The Apache License, Version 2.0" or something very similar, STOP. Ask Hixie for adivce on how to proceed. -1. Copy or move the `lib/` directory to `src/third_party/android_embedding_dependencies/`, +1. Copy or move the `lib/` directory to `src/flutter/third_party/android_embedding_dependencies/`, overwriting its contents, and ensure the Android build still works. 1. Run `cipd create --pkg-def cipd.yaml -tag last_updated:"$version_tag"` where `$version_tag` is the output of `date +%Y-%m-%dT%T%z`. diff --git a/engine/src/flutter/tools/cipd/android_embedding_bundle/build.gradle b/engine/src/flutter/tools/cipd/android_embedding_bundle/build.gradle index 78edce934ef..e14dd4095d5 100644 --- a/engine/src/flutter/tools/cipd/android_embedding_bundle/build.gradle +++ b/engine/src/flutter/tools/cipd/android_embedding_bundle/build.gradle @@ -33,6 +33,7 @@ allprojects { apply plugin: "com.android.application" android { + namespace "io.flutter.licensecheck" compileSdk 36 } diff --git a/examples/api/lib/material/navigation_bar/navigation_bar.2.dart b/examples/api/lib/material/navigation_bar/navigation_bar.2.dart index f723b309e9b..29285c71ef2 100644 --- a/examples/api/lib/material/navigation_bar/navigation_bar.2.dart +++ b/examples/api/lib/material/navigation_bar/navigation_bar.2.dart @@ -78,7 +78,7 @@ class _HomeState extends State with TickerProviderStateMixin { @override Widget build(BuildContext context) { return NavigatorPopHandler( - onPop: () { + onPopWithResult: (void result) { final NavigatorState navigator = navigatorKeys[selectedIndex].currentState!; navigator.pop(); }, diff --git a/examples/multiple_windows/lib/app/main_window.dart b/examples/multiple_windows/lib/app/main_window.dart index c33e1d12e48..9d42ab20c13 100644 --- a/examples/multiple_windows/lib/app/main_window.dart +++ b/examples/multiple_windows/lib/app/main_window.dart @@ -96,12 +96,14 @@ class _WindowsTable extends StatelessWidget { context: context, controller: regular, ), + DialogWindowController() => throw UnimplementedError(), }; } static String _getWindowTypeName(BaseWindowController controller) { return switch (controller) { RegularWindowController() => 'Regular', + DialogWindowController() => 'Dialog', }; } diff --git a/examples/multiple_windows/lib/app/window_content.dart b/examples/multiple_windows/lib/app/window_content.dart index 72ea7fd5990..880b5529728 100644 --- a/examples/multiple_windows/lib/app/window_content.dart +++ b/examples/multiple_windows/lib/app/window_content.dart @@ -33,6 +33,7 @@ class WindowContent extends StatelessWidget { controller: regular, child: MaterialApp(home: RegularWindowContent(window: regular)), ), + DialogWindowController() => throw UnimplementedError(), }; } } diff --git a/packages/flutter/lib/src/cupertino/radio.dart b/packages/flutter/lib/src/cupertino/radio.dart index 392ad897950..00edeecb239 100644 --- a/packages/flutter/lib/src/cupertino/radio.dart +++ b/packages/flutter/lib/src/cupertino/radio.dart @@ -66,23 +66,21 @@ const List _kDisabledDarkGradientOpacities = [0.08, 0.14]; /// deselected. The values are of type `T`, the type parameter of the /// [CupertinoRadio] class. Enums are commonly used for this purpose. /// -/// The radio button itself does not maintain any state. Instead, selecting the -/// radio invokes the [onChanged] callback, passing [value] as a parameter. If -/// [groupValue] and [value] match, this radio will be selected. Most widgets -/// will respond to [onChanged] by calling [State.setState] to update the -/// radio button's [groupValue]. +/// This widget typically has a [RadioGroup] ancestor, which takes in a +/// [RadioGroup.groupValue], and the [CupertinoRadio] under it with matching +/// [value] will be selected. /// /// {@tool dartpad} /// Here is an example of CupertinoRadio widgets wrapped in CupertinoListTiles. /// -/// The currently selected character is passed into `groupValue`, which is +/// The currently selected character is passed into `RadioGroup.groupValue`, which is /// maintained by the example's `State`. In this case, the first [CupertinoRadio] /// will start off selected because `_character` is initialized to /// `SingingCharacter.lafayette`. /// /// If the second radio button is pressed, the example's state is updated /// with `setState`, updating `_character` to `SingingCharacter.jefferson`. -/// This causes the buttons to rebuild with the updated `groupValue`, and +/// This causes the buttons to rebuild with the updated `RadioGroup.groupValue`, and /// therefore the selection of the second button. /// /// ** See code in examples/api/lib/cupertino/radio/cupertino_radio.0.dart ** diff --git a/packages/flutter/lib/src/material/radio.dart b/packages/flutter/lib/src/material/radio.dart index fb84347356f..9207d34e67d 100644 --- a/packages/flutter/lib/src/material/radio.dart +++ b/packages/flutter/lib/src/material/radio.dart @@ -55,7 +55,7 @@ const double _kInnerRadius = 4.5; /// /// If the second radio button is pressed, the example's state is updated /// with `setState`, updating `_character` to `SingingCharacter.jefferson`. -/// This causes the buttons to rebuild with the updated `groupValue`, and +/// This causes the buttons to rebuild with the updated `RadioGroup.groupValue`, and /// therefore the selection of the second button. /// /// Requires one of its ancestors to be a [Material] widget. diff --git a/packages/flutter/lib/src/material/radio_list_tile.dart b/packages/flutter/lib/src/material/radio_list_tile.dart index f217d6867a7..6a3c756282e 100644 --- a/packages/flutter/lib/src/material/radio_list_tile.dart +++ b/packages/flutter/lib/src/material/radio_list_tile.dart @@ -50,7 +50,7 @@ enum _RadioType { material, adaptive } /// This widget does not coordinate the [selected] state and the /// [checked] state; to have the list tile appear selected when the /// radio button is the selected radio button, set [selected] to true -/// when [value] matches [groupValue]. +/// when [value] matches [RadioGroup.groupValue]. /// /// The radio button is shown on the left by default in left-to-right languages /// (i.e. the leading edge). This can be changed using [controlAffinity]. The diff --git a/packages/flutter/lib/src/widgets/_window.dart b/packages/flutter/lib/src/widgets/_window.dart index 5540b8ef6b8..05ff9d36052 100644 --- a/packages/flutter/lib/src/widgets/_window.dart +++ b/packages/flutter/lib/src/widgets/_window.dart @@ -159,7 +159,9 @@ mixin class RegularWindowControllerDelegate { /// {@tool snippet} /// An example usage might look like: /// +/// /// ```dart +/// // TODO(mattkae): remove invalid_use_of_internal_member ignore comment when this API is stable. /// // ignore_for_file: invalid_use_of_internal_member /// import 'package:flutter/widgets.dart'; /// import 'package:flutter/material.dart'; @@ -181,7 +183,7 @@ mixin class RegularWindowControllerDelegate { /// {@end-tool} /// /// Children of a [RegularWindow] widget can access the [RegularWindowController] -/// via the [WindowControllerScope] inherited widget. +/// via the [WindowScope] inherited widget. /// /// {@macro flutter.widgets.windowing.experimental} @internal @@ -190,6 +192,7 @@ abstract class RegularWindowController extends BaseWindowController { /// /// Upon construction, the window is created by the platform. /// + /// {@template flutter.widgets.windowing.constraints} /// The [preferredSize] is the preferred content size of the window. /// This might not be honored by the platform. This is the size that /// the platform will try to apply to the window when it is created. In contrast, @@ -209,6 +212,7 @@ abstract class RegularWindowController extends BaseWindowController { /// /// If both [preferredSize] and [preferredConstraints] are null, /// then the platform will use its own default size for the window. + /// {@endtemplate} /// /// The [title] argument configures the window's initial title. /// If omitted, some platforms might fall back to the app's name. @@ -372,6 +376,250 @@ abstract class RegularWindowController extends BaseWindowController { void setFullscreen(bool fullscreen, {Display? display}); } +/// Delegate class for dialog window controller. +/// +/// {@macro flutter.widgets.windowing.experimental} +/// +/// See also: +/// +/// * [DialogWindowController], the controller that creates and manages dialog windows. +/// * [DialogWindow], the widget for a dialog window. +/// * [RegularWindowControllerDelegate], the delegate for regular window controllers. +@internal +mixin class DialogWindowControllerDelegate { + /// Invoked when the user attempts to close the window. + /// + /// The default implementation destroys the window. Subclasses + /// can override the behavior to delay or prevent the window from closing. + /// + /// {@macro flutter.widgets.windowing.experimental} + /// + /// See also: + /// + /// * [onWindowDestroyed], which is invoked after the window is closed. + @internal + void onWindowCloseRequested(DialogWindowController controller) { + if (!isWindowingEnabled) { + throw UnsupportedError(_kWindowingDisabledErrorMessage); + } + + controller.destroy(); + } + + /// Invoked after the window is closed. + /// + /// {@macro flutter.widgets.windowing.experimental} + /// + /// See also: + /// + /// * [onWindowCloseRequested], which is invoked when the user attempts to close the window. + @internal + void onWindowDestroyed() { + if (!isWindowingEnabled) { + throw UnsupportedError(_kWindowingDisabledErrorMessage); + } + } +} + +/// A controller for a dialog window. +/// +/// Two types of dialogs are supported: +/// * Modal dialogs: created with a non-null parent. These dialogs are modal +/// to the parent, do not have a system menu, and are not selectable from the +/// window switcher. +/// * Modeless dialogs: created with a null parent. These dialogs can be +/// minimized (but not maximized), and have a disabled close button. +/// +/// This class does not interact with the widget tree. Instead, it is typically +/// provided to the [DialogWindow] widget, which renders the content inside the +/// dialog window. +/// +/// The user of this class is responsible for managing the lifecycle of the window. +/// When the window is no longer needed, the user should call [destroy] on this +/// controller to release the resources associated with the window. +/// +/// {@tool snippet} +/// An example usage might look like: +/// +/// ```dart +/// // TODO(mattkae): remove invalid_use_of_internal_member ignore comment when this API is stable. +/// // ignore_for_file: invalid_use_of_internal_member +/// import 'package:flutter/widgets.dart'; +/// import 'package:flutter/material.dart'; +/// import 'package:flutter/src/widgets/_window.dart'; +/// +/// void main() { +/// runWidget( +/// RegularWindow( +/// controller: RegularWindowController( +/// preferredSize: const Size(800, 600), +/// preferredConstraints: const BoxConstraints(minWidth: 640, minHeight: 480), +/// title: 'Example Window', +/// ), +/// child: const MyApp() +/// ) +/// ); +/// } +/// +/// class MyApp extends StatelessWidget { +/// const MyApp({super.key}); +/// +/// @override +/// Widget build(BuildContext context) { +/// return MaterialApp( +/// home: DialogWindow( +/// controller: DialogWindowController( +/// preferredSize: const Size(400, 300), +/// parent: WindowScope.of(context), +/// title: 'Example Dialog' +/// ), +/// child: const Text('Hello, World!') +/// ) +/// ); +/// } +/// } +/// ``` +/// {@end-tool} +/// +/// Children of a [DialogWindow] widget can access the [DialogWindowController] +/// via the [WindowScope] inherited widget. +/// +/// {@macro flutter.widgets.windowing.experimental} +abstract class DialogWindowController extends BaseWindowController { + /// Creates a [DialogWindowController] with the provided properties. + /// + /// Upon construction, the window is created by the platform. + /// + /// {@macro flutter.widgets.windowing.constraints} + /// + /// The [parent] argument specifies the parent window of this dialog. + /// + /// If the [parent] is null, then the dialog is modeless. Such dialogs can + /// be minimized but not maximized. They also have a disabled close button. + /// + /// If the [parent] is non-null, then the dialog is modal to the parent. + /// Such dialogs do not have a system menu. They are also not selectable + /// from the window switcher and they are closed when the parent is closed. + /// + /// The [title] argument configures the window's initial title. + /// If omitted, some platforms might fall back to the app's name. + /// + /// The [delegate] argument can be used to listen to the window's + /// lifecycle. For example, it can be used to save state before + /// a window is closed. + /// + /// {@macro flutter.widgets.windowing.experimental} + factory DialogWindowController({ + Size? preferredSize, + BoxConstraints? preferredConstraints, + BaseWindowController? parent, + String? title, + DialogWindowControllerDelegate? delegate, + }) { + WidgetsFlutterBinding.ensureInitialized(); + final WindowingOwner owner = WidgetsBinding.instance.windowingOwner; + return owner.createDialogWindowController( + delegate: delegate ?? DialogWindowControllerDelegate(), + preferredSize: preferredSize, + preferredConstraints: preferredConstraints, + title: title, + parent: parent, + ); + } + + /// Creates an empty [DialogWindowController]. + /// + /// This method is only intended to be used by subclasses of the + /// [DialogWindowController]. + /// + /// Users who want to instantiate a new [DialogWindowController] should + /// always use the factory method to create a controller that is valid + /// for their particular platform. + /// + /// {@macro flutter.widgets.windowing.experimental} + @internal + @protected + DialogWindowController.empty(); + + /// The parent controller of this dialog, if any. + /// + /// If null, this dialog is modeless. + /// If non-null, this dialog is modal to the parent. + BaseWindowController? get parent; + + /// The current title of the window. + /// + /// This might differ from the requested title. + /// + /// {@macro flutter.widgets.windowing.experimental} + @internal + String get title; + + /// Whether the window is currently activated. + /// + /// If `true` this means that the window is currently focused and + /// can receive user input. + /// + /// {@macro flutter.widgets.windowing.experimental} + @internal + bool get isActivated; + + /// Whether or not window is currently minimized. + /// + /// {@macro flutter.widgets.windowing.experimental} + @internal + bool get isMinimized; + + /// Request change to the content size of the window. + /// + /// The [size] describes the new requested window size. If the size disagrees + /// with the current constraints placed upon the window, the platform might + /// clamp the size within the constraints. + /// + /// The platform is free to ignore this request. + /// + /// {@macro flutter.widgets.windowing.experimental} + @internal + void setSize(Size size); + + /// Request change to the constraints of the window. + /// + /// The [constraints] describes the new constraints that the window should + /// satisfy. If the constraints disagree with the current size of the window, + /// the platform might resize the window to satisfy the new constraints. + /// + /// The platform is free to ignore this request. + /// + /// {@macro flutter.widgets.windowing.experimental} + @internal + void setConstraints(BoxConstraints constraints); + + /// Request change for the window title. + /// + /// {@macro flutter.widgets.windowing.experimental} + @internal + void setTitle(String title); + + /// Requests that the window be displayed in its current size and position. + /// + /// The platform may also give the window input focus and bring it to the + /// top of the window stack. However, this behavior is platform-dependent. + /// + /// If the window is minimized, the window returns to the size and position + /// that it had before that state was applied. The window will also be + /// brought to the top of the window stack. + /// + /// {@macro flutter.widgets.windowing.experimental} + @internal + void activate(); + + /// Requests window to be minimized. + /// + /// {@macro flutter.widgets.windowing.experimental} + @internal + void setMinimized(bool minimized); +} + /// [WindowingOwner] is responsible for creating and managing window controllers. /// /// A custom implementation can be provided by setting [WidgetsBinding.windowingOwner]. @@ -394,6 +642,22 @@ abstract class WindowingOwner { String? title, }); + /// Creates a [DialogWindowController] with the provided properties. + /// + /// Most app developers should use [DialogWindowController]'s constructor + /// instead of calling this method directly. This method allows platforms + /// to inject platform-specific logic. + /// + /// {@macro flutter.widgets.windowing.experimental} + @internal + DialogWindowController createDialogWindowController({ + required DialogWindowControllerDelegate delegate, + Size? preferredSize, + BoxConstraints? preferredConstraints, + BaseWindowController? parent, + String? title, + }); + /// Returns whether the application has any top level windows created by this /// windowing owner. /// @@ -435,6 +699,17 @@ class _WindowingOwnerUnsupported extends WindowingOwner { throw UnsupportedError(errorMessage); } + @override + DialogWindowController createDialogWindowController({ + required DialogWindowControllerDelegate delegate, + Size? preferredSize, + BoxConstraints? preferredConstraints, + BaseWindowController? parent, + String? title, + }) { + throw UnsupportedError(errorMessage); + } + @override bool hasTopLevelWindows() { throw UnsupportedError(errorMessage); @@ -458,6 +733,7 @@ class _WindowingOwnerUnsupported extends WindowingOwner { /// An example usage might look like: /// /// ```dart +/// // TODO(mattkae): remove invalid_use_of_internal_member ignore comment when this API is stable. /// // ignore_for_file: invalid_use_of_internal_member /// import 'package:flutter/widgets.dart'; /// import 'package:flutter/material.dart'; @@ -523,6 +799,107 @@ class RegularWindow extends StatelessWidget { } } +/// The [DialogWindow] widget provides a way to render a dialog window in the +/// widget tree. +/// +/// The provided [controller] creates the native window that backs +/// the widget. The [child] widget is rendered into this newly created window. +/// +/// When a [DialogWindow] widget is removed from the tree, the window that was created +/// by the [controller] remains valid until the caller destroys it by calling +/// [DialogWindowController.destroy]. +/// +/// Widgets in the same tree as the [child] widget will have access to the +/// [DialogWindowController] via the [WindowScope] widget. +/// +/// {@tool snippet} +/// An example usage might look like: +/// +/// ```dart +/// // TODO(mattkae): remove invalid_use_of_internal_member ignore comment when this API is stable. +/// // ignore_for_file: invalid_use_of_internal_member +/// import 'package:flutter/widgets.dart'; +/// import 'package:flutter/material.dart'; +/// import 'package:flutter/src/widgets/_window.dart'; +/// +/// void main() { +/// runWidget( +/// RegularWindow( +/// controller: RegularWindowController( +/// preferredSize: const Size(800, 600), +/// preferredConstraints: const BoxConstraints(minWidth: 640, minHeight: 480), +/// title: 'Example Window', +/// ), +/// child: const MyApp() +/// ) +/// ); +/// } +/// +/// class MyApp extends StatelessWidget { +/// const MyApp({super.key}); +/// +/// @override +/// Widget build(BuildContext context) { +/// return MaterialApp( +/// home: DialogWindow( +/// controller: DialogWindowController( +/// preferredSize: const Size(400, 300), +/// parent: WindowScope.of(context), +/// title: 'Example Dialog' +/// ), +/// child: const Text('Hello, World!') +/// ) +/// ); +/// } +/// } +/// ``` +/// {@end-tool} +/// +/// {@macro flutter.widgets.windowing.experimental} +@internal +class DialogWindow extends StatelessWidget { + /// Creates a dialog window widget. + /// + /// The [controller] creates the native backing window into which the + /// [child] widget is rendered. + /// + /// It is up to the caller to destroy the window by calling + /// [DialogWindowController.destroy] when the window is no longer needed. + /// + /// {@macro flutter.widgets.windowing.experimental} + @internal + DialogWindow({super.key, required this.controller, required this.child}) { + if (!isWindowingEnabled) { + throw UnsupportedError(_kWindowingDisabledErrorMessage); + } + } + + /// Controller for this widget. + /// + /// {@macro flutter.widgets.windowing.experimental} + @internal + final DialogWindowController controller; + + /// The content rendered into this window. + /// + /// {@macro flutter.widgets.windowing.experimental} + @internal + final Widget child; + + /// {@macro flutter.widgets.windowing.experimental} + @internal + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: controller, + builder: (BuildContext context, Widget? widget) => WindowScope( + controller: controller, + child: View(view: controller.rootView, child: child), + ), + ); + } +} + enum _WindowControllerAspect { contentSize, title, activated, maximized, minimized, fullscreen } /// Provides descendants with access to the [BaseWindowController] associated with @@ -537,6 +914,7 @@ enum _WindowControllerAspect { contentSize, title, activated, maximized, minimiz /// See also: /// /// * [RegularWindow], the widget to create a regular window. +/// * [DialogWindow], the widget to create a dialog window. @internal class WindowScope extends InheritedModel<_WindowControllerAspect> { /// Creates a new [WindowScope]. @@ -565,8 +943,8 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> { /// Returns the [BaseWindowController] for the window that hosts the given context. /// - /// {@template flutter.widgets.windowing.windowControllerScope.of} - /// If there is no [WindowControllerScope] in scope, this method + /// {@template flutter.widgets.windowing.WindowScope.of} + /// If there is no [WindowScope] in scope, this method /// will throw a [TypeError] exception in release builds, and throws /// a descriptive [FlutterError] in debug builds. /// @@ -580,7 +958,9 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> { /// See also: /// /// * [RegularWindowController], the controller for regular top-level windows. + /// * [DialogWindowController], the controller for dialog windows. /// * [RegularWindow], the widget for a regular window. + /// * [DialogWindow], the widget for a dialog window. /// * [maybeOf], which doesn't throw or assert if it doesn't find a /// [WindowScope] ancestor. It returns null instead. @internal @@ -595,7 +975,9 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> { /// See also: /// /// * [RegularWindowController], the controller for regular top-level windows. + /// * [DialogWindowController], the controller for dialog windows. /// * [RegularWindow], the widget for a regular window. + /// * [DialogWindow], the widget for a dialog window. /// * [of], which will throw if it doesn't find a [WindowScope] ancestor, /// instead of returning null. @internal @@ -648,6 +1030,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> { final BaseWindowController controller = _of(context, _WindowControllerAspect.title); return switch (controller) { RegularWindowController() => controller.title, + DialogWindowController() => controller.title, }; } @@ -668,6 +1051,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> { return switch (controller) { RegularWindowController() => controller.title, + DialogWindowController() => controller.title, }; } @@ -689,6 +1073,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> { final BaseWindowController controller = _of(context, _WindowControllerAspect.activated); return switch (controller) { RegularWindowController() => controller.isActivated, + DialogWindowController() => controller.isActivated, }; } @@ -710,6 +1095,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> { return switch (controller) { RegularWindowController() => controller.isActivated, + DialogWindowController() => controller.isActivated, }; } @@ -731,6 +1117,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> { final BaseWindowController controller = _of(context, _WindowControllerAspect.minimized); return switch (controller) { RegularWindowController() => controller.isMinimized, + DialogWindowController() => controller.isMinimized, }; } @@ -752,6 +1139,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> { return switch (controller) { RegularWindowController() => controller.isMinimized, + DialogWindowController() => controller.isMinimized, }; } @@ -773,6 +1161,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> { final BaseWindowController controller = _of(context, _WindowControllerAspect.maximized); return switch (controller) { RegularWindowController() => controller.isMaximized, + DialogWindowController() => false, }; } @@ -794,6 +1183,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> { return switch (controller) { RegularWindowController() => controller.isMaximized, + DialogWindowController() => false, }; } @@ -816,6 +1206,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> { return switch (controller) { RegularWindowController() => controller.isFullscreen, + DialogWindowController() => false, }; } @@ -837,6 +1228,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> { return switch (controller) { RegularWindowController() => controller.isFullscreen, + DialogWindowController() => false, }; } @@ -898,26 +1290,34 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> { _WindowControllerAspect.title => switch (controller) { final RegularWindowController regular => regular.title != (oldWidget.controller as RegularWindowController).title, + final DialogWindowController dialog => + dialog.title != (oldWidget.controller as DialogWindowController).title, }, _WindowControllerAspect.activated => switch (controller) { final RegularWindowController regular => regular.isActivated != (oldWidget.controller as RegularWindowController).isActivated, + final DialogWindowController dialog => + dialog.isActivated != (oldWidget.controller as DialogWindowController).isActivated, }, _WindowControllerAspect.maximized => switch (controller) { final RegularWindowController regular => regular.isMaximized != (oldWidget.controller as RegularWindowController).isMaximized, + DialogWindowController() => false, }, _WindowControllerAspect.minimized => switch (controller) { final RegularWindowController regular => regular.isMinimized != (oldWidget.controller as RegularWindowController).isMinimized, + final DialogWindowController dialog => + dialog.isMinimized != (oldWidget.controller as DialogWindowController).isMinimized, }, _WindowControllerAspect.fullscreen => switch (controller) { final RegularWindowController regular => regular.isFullscreen != (oldWidget.controller as RegularWindowController).isFullscreen, + DialogWindowController() => false, }, }, ); diff --git a/packages/flutter/lib/src/widgets/_window_win32.dart b/packages/flutter/lib/src/widgets/_window_win32.dart index 1d6a81c3ccf..46647a630a6 100644 --- a/packages/flutter/lib/src/widgets/_window_win32.dart +++ b/packages/flutter/lib/src/widgets/_window_win32.dart @@ -148,6 +148,18 @@ class WindowingOwnerWin32 extends WindowingOwner { ); } + @internal + @override + DialogWindowController createDialogWindowController({ + required DialogWindowControllerDelegate delegate, + Size? preferredSize, + BoxConstraints? preferredConstraints, + BaseWindowController? parent, + String? title, + }) { + throw UnimplementedError('Dialog windows are not yet implemented on Windows.'); + } + /// Register a new [WindowsMessageHandler]. /// /// The handler will be triggered for unhandled messages for all top level diff --git a/packages/flutter/lib/src/widgets/localizations.dart b/packages/flutter/lib/src/widgets/localizations.dart index 2ca7600107b..9cbe30a2ff3 100644 --- a/packages/flutter/lib/src/widgets/localizations.dart +++ b/packages/flutter/lib/src/widgets/localizations.dart @@ -634,6 +634,14 @@ class _LocalizationsState extends State { Locale? get locale => _locale; Locale? _locale; + set locale(Locale? locale) { + assert(locale != null); + if (_locale == locale) { + return; + } + WidgetsBinding.instance.platformDispatcher.setApplicationLocale(locale!); + _locale = locale; + } @override void initState() { @@ -668,7 +676,7 @@ class _LocalizationsState extends State { void load(Locale locale) { final Iterable> delegates = widget.delegates; if (delegates.isEmpty) { - _locale = locale; + this.locale = locale; return; } @@ -681,7 +689,7 @@ class _LocalizationsState extends State { if (typeToResources != null) { // All of the delegates' resources loaded synchronously. _typeToResources = typeToResources!; - _locale = locale; + this.locale = locale; } else { // - Don't rebuild the dependent widgets until the resources for the new locale // have finished loading. Until then the old locale will continue to be used. @@ -692,7 +700,7 @@ class _LocalizationsState extends State { if (mounted) { setState(() { _typeToResources = value; - _locale = locale; + this.locale = locale; }); } RendererBinding.instance.allowFirstFrame(); diff --git a/packages/flutter/test/widgets/localizations_test.dart b/packages/flutter/test/widgets/localizations_test.dart index cdc639c9b5d..8896d6f5c59 100644 --- a/packages/flutter/test/widgets/localizations_test.dart +++ b/packages/flutter/test/widgets/localizations_test.dart @@ -61,6 +61,24 @@ void main() { expect(find.text('loaded'), findsOneWidget); }); + testWidgets('Locale is sent to engine if this is a top level Localizations', ( + WidgetTester tester, + ) async { + final FakeLocalizationsDelegate delegate = FakeLocalizationsDelegate(); + await tester.pumpWidget( + Localizations( + locale: const Locale('fo'), + isApplicationLevel: true, + delegates: >[WidgetsLocalizationsDelegate(), delegate], + child: const Text('loaded'), + ), + ); + delegate.completer.complete('foo'); + await tester.idle(); + await tester.pump(); + expect(tester.binding.platformDispatcher.applicationLocale, const Locale('fo')); + }); + testWidgets('Localizations.localeOf throws when no localizations exist', ( WidgetTester tester, ) async { diff --git a/packages/flutter/test/widgets/semantics_tester.dart b/packages/flutter/test/widgets/semantics_tester.dart index c10cb419123..580e4fdfe87 100644 --- a/packages/flutter/test/widgets/semantics_tester.dart +++ b/packages/flutter/test/widgets/semantics_tester.dart @@ -9,7 +9,7 @@ import 'package:flutter/physics.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; -export 'dart:ui' show SemanticsAction, SemanticsFlag; +export 'dart:ui' show SemanticsAction, SemanticsFlag, SemanticsFlags; export 'package:flutter/rendering.dart' show SemanticsData; const String _matcherHelp = @@ -62,7 +62,7 @@ class TestSemantics { this.currentValueLength, this.identifier = '', this.hintOverrides, - }) : assert(flags is int || flags is List), + }) : assert(flags is int || flags is List || flags is SemanticsFlags), assert(actions is int || actions is List), tags = tags?.toSet() ?? {}; @@ -95,7 +95,7 @@ class TestSemantics { this.identifier = '', this.hintOverrides, }) : id = 0, - assert(flags is int || flags is List), + assert(flags is int || flags is List || flags is SemanticsFlags), assert(actions is int || actions is List), rect = TestSemantics.rootRect, tags = tags?.toSet() ?? {}; @@ -138,7 +138,7 @@ class TestSemantics { this.currentValueLength, this.identifier = '', this.hintOverrides, - }) : assert(flags is int || flags is List), + }) : assert(flags is int || flags is List || flags is SemanticsFlags), assert(actions is int || actions is List), transform = _applyRootChildScale(transform), tags = tags?.toSet() ?? {}; @@ -149,12 +149,15 @@ class TestSemantics { /// they are created. final int? id; - /// The [SemanticsFlag]s set on this node. + /// The SemanticsFlags on this node. /// - /// There are two ways to specify this property: as an `int` that encodes the - /// flags as a bit field, or as a `List` that are _on_. + /// There are three ways to specify this property: as an `int` that encodes the + /// flags as a bit field, or as a `List` that are _on_, or as a `SemanticsFlags`. /// - /// Using `List` is recommended due to better readability. + /// Using `SemanticsFlags` is recommended. + /// + /// The `int` and `List` types are considered deprecated as they + /// have limited bits and only support the first 31 flags. final dynamic flags; /// The [SemanticsAction]s set on this node. @@ -323,14 +326,25 @@ class TestSemantics { final SemanticsData nodeData = node.getSemanticsData(); - final int flagsBitmask = flags is int - ? flags as int - : (flags as List).fold( - 0, - (int bitmask, SemanticsFlag flag) => bitmask | flag.index, - ); - if (flagsBitmask != nodeData.flags) { - return fail('expected node id $id to have flags $flags but found flags ${nodeData.flags}.'); + if (flags is SemanticsFlags) { + if (flags != nodeData.flagsCollection) { + return fail( + 'expected node id $id to have flags $flags but found flags ${nodeData.flagsCollection}.', + ); + } + } + // the bitmask flags only support first 31 flags. + else { + final int flagsBitmask = flags is int + ? flags as int + : (flags as List).fold( + 0, + (int bitmask, SemanticsFlag flag) => bitmask | flag.index, + ); + + if (flagsBitmask != nodeData.flags) { + return fail('expected node id $id to have flags $flags but found flags ${nodeData.flags}.'); + } } final int actionsBitmask = actions is int @@ -505,8 +519,9 @@ class TestSemantics { if (id != null) { buf.writeln('$indent id: $id,'); } - if (flags is int && flags != 0 || - flags is List && (flags as List).isNotEmpty) { + if ((flags is int && flags != 0) || + (flags is List && (flags as List).isNotEmpty) || + (flags is SemanticsFlags && (flags as SemanticsFlags) != SemanticsFlags.none)) { buf.writeln('$indent flags: ${SemanticsTester._flagsToSemanticsFlagExpression(flags)},'); } if (actions is int && actions != 0 || @@ -659,6 +674,7 @@ class SemanticsTester { TextDirection? textDirection, List? actions, List? flags, + SemanticsFlags? flagsCollection, Set? tags, double? scrollPosition, double? scrollExtentMax, @@ -719,7 +735,16 @@ class SemanticsTester { return false; } } - if (flags != null) { + + if (flagsCollection != null) { + final SemanticsFlags expectedFlags = flagsCollection; + final SemanticsFlags actualFlags = node.getSemanticsData().flagsCollection; + if (expectedFlags != actualFlags) { + return false; + } + } + // `flags` are deprecated and only support the first 31 flags. + else if (flags != null) { final int expectedFlags = flags.fold( 0, (int value, SemanticsFlag flag) => value | flag.index, @@ -827,7 +852,9 @@ class SemanticsTester { static String _flagsToSemanticsFlagExpression(dynamic flags) { Iterable list; - if (flags is int) { + if (flags is SemanticsFlags) { + return '[${flags.toStrings().join(', ')}]'; + } else if (flags is int) { list = SemanticsFlag.values.where((SemanticsFlag flag) => (flag.index & flags) != 0); } else { list = flags as List; @@ -1048,6 +1075,7 @@ class _IncludesNodeWith extends Matcher { this.textDirection, this.actions, this.flags, + this.flagsCollection, this.tags, this.scrollPosition, this.scrollExtentMax, @@ -1060,6 +1088,7 @@ class _IncludesNodeWith extends Matcher { value != null || actions != null || flags != null || + flagsCollection != null || tags != null || increasedValue != null || decreasedValue != null || @@ -1081,6 +1110,7 @@ class _IncludesNodeWith extends Matcher { final TextDirection? textDirection; final List? actions; final List? flags; + final SemanticsFlags? flagsCollection; final Set? tags; final double? scrollPosition; final double? scrollExtentMax; @@ -1104,6 +1134,7 @@ class _IncludesNodeWith extends Matcher { textDirection: textDirection, actions: actions, flags: flags, + flagsCollection: flagsCollection, tags: tags, scrollPosition: scrollPosition, scrollExtentMax: scrollExtentMax, @@ -1168,6 +1199,7 @@ Matcher includesNodeWith({ TextDirection? textDirection, List? actions, List? flags, + SemanticsFlags? flagsCollection, Set? tags, double? scrollPosition, double? scrollExtentMax, @@ -1188,6 +1220,7 @@ Matcher includesNodeWith({ decreasedValue: decreasedValue, actions: actions, flags: flags, + flagsCollection: flagsCollection, tags: tags, scrollPosition: scrollPosition, scrollExtentMax: scrollExtentMax, diff --git a/packages/flutter/test/widgets/semantics_tester_test.dart b/packages/flutter/test/widgets/semantics_tester_test.dart index 908daaa0a61..f25ca1c6bcd 100644 --- a/packages/flutter/test/widgets/semantics_tester_test.dart +++ b/packages/flutter/test/widgets/semantics_tester_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:ui'; + import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -46,4 +48,105 @@ void main() { ); semantics.dispose(); }); + + testWidgets('Semantics tester support flags as an int', (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + + await tester.pumpWidget( + Semantics( + container: true, + child: Semantics( + label: 'test1', + textDirection: TextDirection.ltr, + selected: true, + child: Container(), + ), + ), + ); + + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: [ + TestSemantics.rootChild( + id: 1, + label: 'test1', + rect: TestSemantics.fullScreen, + flags: SemanticsFlag.hasSelectedState.index | SemanticsFlag.isSelected.index, + ), + ], + ), + ), + ); + semantics.dispose(); + }); + + testWidgets('Semantics tester support flags as a list of SemanticsFlag', ( + WidgetTester tester, + ) async { + final SemanticsTester semantics = SemanticsTester(tester); + + await tester.pumpWidget( + Semantics( + container: true, + child: Semantics( + label: 'test1', + textDirection: TextDirection.ltr, + selected: true, + child: Container(), + ), + ), + ); + + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: [ + TestSemantics.rootChild( + id: 1, + label: 'test1', + rect: TestSemantics.fullScreen, + flags: [SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], + ), + ], + ), + ), + ); + semantics.dispose(); + }); + + testWidgets('Semantics tester support flags as a SemanticsFlags', (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + + await tester.pumpWidget( + Semantics( + container: true, + child: Semantics( + label: 'test1', + textDirection: TextDirection.ltr, + selected: true, + child: Container(), + ), + ), + ); + + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: [ + TestSemantics.rootChild( + id: 1, + label: 'test1', + rect: TestSemantics.fullScreen, + flags: SemanticsFlags(isSelected: Tristate.isTrue), + ), + ], + ), + ), + ); + semantics.dispose(); + }); } diff --git a/packages/flutter/test/widgets/windowing_test.dart b/packages/flutter/test/widgets/windowing_test.dart index ca8995bed2d..c14aa3b833a 100644 --- a/packages/flutter/test/widgets/windowing_test.dart +++ b/packages/flutter/test/widgets/windowing_test.dart @@ -7,6 +7,9 @@ import 'package:flutter/src/foundation/_features.dart' show isWindowingEnabled; import 'package:flutter/src/widgets/_window.dart' show BaseWindowController, + DialogWindow, + DialogWindowController, + DialogWindowControllerDelegate, RegularWindow, RegularWindowController, RegularWindowControllerDelegate, @@ -18,8 +21,8 @@ import 'package:flutter_test/flutter_test.dart'; import 'multi_view_testing.dart'; -class _StubWindowController extends RegularWindowController { - _StubWindowController(WidgetTester tester) : super.empty() { +class _StubRegularWindowController extends RegularWindowController { + _StubRegularWindowController(WidgetTester tester) : super.empty() { rootView = FakeView(tester.view); } @@ -66,6 +69,45 @@ class _StubWindowController extends RegularWindowController { void destroy() {} } +class _StubDialogWindowController extends DialogWindowController { + _StubDialogWindowController(WidgetTester tester) : super.empty() { + rootView = FakeView(tester.view); + } + + @override + BaseWindowController? get parent => null; + + @override + Size get contentSize => Size.zero; + + @override + String get title => 'Stub Window'; + + @override + bool get isActivated => true; + + @override + bool get isMinimized => false; + + @override + void setSize(Size size) {} + + @override + void setConstraints(BoxConstraints constraints) {} + + @override + void setTitle(String title) {} + + @override + void activate() {} + + @override + void setMinimized(bool minimized) {} + + @override + void destroy() {} +} + void main() { group('Windowing', () { group('isWindowingEnabled is false', () { @@ -86,6 +128,14 @@ void main() { ); }); + test('default WindowingOwner throws when accessing createDialogWindowController', () { + final WindowingOwner owner = createDefaultWindowingOwner(); + expect( + () => owner.createDialogWindowController(delegate: DialogWindowControllerDelegate()), + throwsUnsupportedError, + ); + }); + test('default WindowingOwner throws when accessing hasTopLevelWindows', () { final WindowingOwner owner = createDefaultWindowingOwner(); expect(() => owner.hasTopLevelWindows(), throwsUnsupportedError); @@ -93,7 +143,20 @@ void main() { testWidgets('RegularWindow throws UnsupportedError', (WidgetTester tester) async { expect( - () => RegularWindow(controller: _StubWindowController(tester), child: const Text('Test')), + () => RegularWindow( + controller: _StubRegularWindowController(tester), + child: const Text('Test'), + ), + throwsUnsupportedError, + ); + }); + + testWidgets('DialogWindow throws UnsupportedError', (WidgetTester tester) async { + expect( + () => DialogWindow( + controller: _StubDialogWindowController(tester), + child: const Text('Test'), + ), throwsUnsupportedError, ); }); @@ -112,7 +175,7 @@ void main() { }); testWidgets('RegularWindow does not throw', (WidgetTester tester) async { - final _StubWindowController controller = _StubWindowController(tester); + final _StubRegularWindowController controller = _StubRegularWindowController(tester); addTearDown(controller.dispose); await tester.pumpWidget( wrapWithView: false, @@ -120,8 +183,17 @@ void main() { ); }); - testWidgets('Can access WindowScope.of', (WidgetTester tester) async { - final _StubWindowController controller = _StubWindowController(tester); + testWidgets('Dialog does not throw', (WidgetTester tester) async { + final _StubDialogWindowController controller = _StubDialogWindowController(tester); + addTearDown(controller.dispose); + await tester.pumpWidget( + wrapWithView: false, + DialogWindow(controller: controller, child: Container()), + ); + }); + + testWidgets('Can access WindowScope.of for regular windows', (WidgetTester tester) async { + final _StubRegularWindowController controller = _StubRegularWindowController(tester); addTearDown(controller.dispose); await tester.pumpWidget( wrapWithView: false, @@ -138,8 +210,28 @@ void main() { ); }); - testWidgets('Can access WindowScope.maybeOf', (WidgetTester tester) async { - final _StubWindowController controller = _StubWindowController(tester); + testWidgets('Can access WindowScope.of for dialog windows', (WidgetTester tester) async { + final _StubDialogWindowController controller = _StubDialogWindowController(tester); + addTearDown(controller.dispose); + await tester.pumpWidget( + wrapWithView: false, + DialogWindow( + controller: controller, + child: Builder( + builder: (BuildContext context) { + final BaseWindowController scope = WindowScope.of(context); + expect(scope, isA()); + return const SizedBox.shrink(); + }, + ), + ), + ); + }); + + testWidgets('Can access WindowScope.maybeOf for regular windows', ( + WidgetTester tester, + ) async { + final _StubRegularWindowController controller = _StubRegularWindowController(tester); addTearDown(controller.dispose); await tester.pumpWidget( wrapWithView: false, @@ -156,8 +248,28 @@ void main() { ); }); - testWidgets('Can access WindowScope.contentSizeOf', (WidgetTester tester) async { - final _StubWindowController controller = _StubWindowController(tester); + testWidgets('Can access WindowScope.maybeOf for dialog windows', (WidgetTester tester) async { + final _StubDialogWindowController controller = _StubDialogWindowController(tester); + addTearDown(controller.dispose); + await tester.pumpWidget( + wrapWithView: false, + DialogWindow( + controller: controller, + child: Builder( + builder: (BuildContext context) { + final BaseWindowController? scope = WindowScope.maybeOf(context); + expect(scope, isA()); + return const SizedBox.shrink(); + }, + ), + ), + ); + }); + + testWidgets('Can access WindowScope.contentSizeOf for regular windows', ( + WidgetTester tester, + ) async { + final _StubRegularWindowController controller = _StubRegularWindowController(tester); addTearDown(controller.dispose); await tester.pumpWidget( wrapWithView: false, @@ -174,8 +286,30 @@ void main() { ); }); - testWidgets('Can access WindowScope.maybeContentSizeOf', (WidgetTester tester) async { - final _StubWindowController controller = _StubWindowController(tester); + testWidgets('Can access WindowScope.contentSizeOf for dialog windows', ( + WidgetTester tester, + ) async { + final _StubDialogWindowController controller = _StubDialogWindowController(tester); + addTearDown(controller.dispose); + await tester.pumpWidget( + wrapWithView: false, + DialogWindow( + controller: controller, + child: Builder( + builder: (BuildContext context) { + final Size size = WindowScope.contentSizeOf(context); + expect(size, equals(Size.zero)); + return const SizedBox.shrink(); + }, + ), + ), + ); + }); + + testWidgets('Can access WindowScope.maybeContentSizeOf for regular windows', ( + WidgetTester tester, + ) async { + final _StubRegularWindowController controller = _StubRegularWindowController(tester); addTearDown(controller.dispose); await tester.pumpWidget( wrapWithView: false, @@ -192,8 +326,30 @@ void main() { ); }); - testWidgets('Can access WindowScope.titleOf', (WidgetTester tester) async { - final _StubWindowController controller = _StubWindowController(tester); + testWidgets('Can access WindowScope.maybeContentSizeOf for dialog windows', ( + WidgetTester tester, + ) async { + final _StubDialogWindowController controller = _StubDialogWindowController(tester); + addTearDown(controller.dispose); + await tester.pumpWidget( + wrapWithView: false, + DialogWindow( + controller: controller, + child: Builder( + builder: (BuildContext context) { + final Size? size = WindowScope.maybeContentSizeOf(context); + expect(size, equals(Size.zero)); + return const SizedBox.shrink(); + }, + ), + ), + ); + }); + + testWidgets('Can access WindowScope.titleOf for regular windows', ( + WidgetTester tester, + ) async { + final _StubRegularWindowController controller = _StubRegularWindowController(tester); addTearDown(controller.dispose); await tester.pumpWidget( wrapWithView: false, @@ -210,8 +366,28 @@ void main() { ); }); - testWidgets('Can access WindowScope.maybeTitleOf', (WidgetTester tester) async { - final _StubWindowController controller = _StubWindowController(tester); + testWidgets('Can access WindowScope.titleOf for dialog windows', (WidgetTester tester) async { + final _StubDialogWindowController controller = _StubDialogWindowController(tester); + addTearDown(controller.dispose); + await tester.pumpWidget( + wrapWithView: false, + DialogWindow( + controller: controller, + child: Builder( + builder: (BuildContext context) { + final String title = WindowScope.titleOf(context); + expect(title, equals('Stub Window')); + return const SizedBox.shrink(); + }, + ), + ), + ); + }); + + testWidgets('Can access WindowScope.maybeTitleOf for regular windows', ( + WidgetTester tester, + ) async { + final _StubRegularWindowController controller = _StubRegularWindowController(tester); addTearDown(controller.dispose); await tester.pumpWidget( wrapWithView: false, @@ -228,8 +404,30 @@ void main() { ); }); - testWidgets('Can access WindowScope.isActivatedOf', (WidgetTester tester) async { - final _StubWindowController controller = _StubWindowController(tester); + testWidgets('Can access WindowScope.maybeTitleOf for dialog windows', ( + WidgetTester tester, + ) async { + final _StubDialogWindowController controller = _StubDialogWindowController(tester); + addTearDown(controller.dispose); + await tester.pumpWidget( + wrapWithView: false, + DialogWindow( + controller: controller, + child: Builder( + builder: (BuildContext context) { + final String? title = WindowScope.maybeTitleOf(context); + expect(title, equals('Stub Window')); + return const SizedBox.shrink(); + }, + ), + ), + ); + }); + + testWidgets('Can access WindowScope.isActivatedOf for regular windows', ( + WidgetTester tester, + ) async { + final _StubRegularWindowController controller = _StubRegularWindowController(tester); addTearDown(controller.dispose); await tester.pumpWidget( wrapWithView: false, @@ -246,8 +444,30 @@ void main() { ); }); - testWidgets('Can access WindowScope.maybeIsActivatedOf', (WidgetTester tester) async { - final _StubWindowController controller = _StubWindowController(tester); + testWidgets('Can access WindowScope.isActivatedOf for dialog windows', ( + WidgetTester tester, + ) async { + final _StubDialogWindowController controller = _StubDialogWindowController(tester); + addTearDown(controller.dispose); + await tester.pumpWidget( + wrapWithView: false, + DialogWindow( + controller: controller, + child: Builder( + builder: (BuildContext context) { + final bool isActivated = WindowScope.isActivatedOf(context); + expect(isActivated, equals(true)); + return const SizedBox.shrink(); + }, + ), + ), + ); + }); + + testWidgets('Can access WindowScope.maybeIsActivatedOf for regular windows', ( + WidgetTester tester, + ) async { + final _StubRegularWindowController controller = _StubRegularWindowController(tester); addTearDown(controller.dispose); await tester.pumpWidget( wrapWithView: false, @@ -264,8 +484,30 @@ void main() { ); }); - testWidgets('Can access WindowScope.isMinimizedOf', (WidgetTester tester) async { - final _StubWindowController controller = _StubWindowController(tester); + testWidgets('Can access WindowScope.maybeIsActivatedOf for dialog windows', ( + WidgetTester tester, + ) async { + final _StubDialogWindowController controller = _StubDialogWindowController(tester); + addTearDown(controller.dispose); + await tester.pumpWidget( + wrapWithView: false, + DialogWindow( + controller: controller, + child: Builder( + builder: (BuildContext context) { + final bool? isActivated = WindowScope.maybeIsActivatedOf(context); + expect(isActivated, equals(true)); + return const SizedBox.shrink(); + }, + ), + ), + ); + }); + + testWidgets('Can access WindowScope.isMinimizedOf for regular windows', ( + WidgetTester tester, + ) async { + final _StubRegularWindowController controller = _StubRegularWindowController(tester); addTearDown(controller.dispose); await tester.pumpWidget( wrapWithView: false, @@ -282,8 +524,30 @@ void main() { ); }); - testWidgets('Can access WindowScope.maybeIsMinimizedOf', (WidgetTester tester) async { - final _StubWindowController controller = _StubWindowController(tester); + testWidgets('Can access WindowScope.isMinimizedOf for dialog windows', ( + WidgetTester tester, + ) async { + final _StubDialogWindowController controller = _StubDialogWindowController(tester); + addTearDown(controller.dispose); + await tester.pumpWidget( + wrapWithView: false, + DialogWindow( + controller: controller, + child: Builder( + builder: (BuildContext context) { + final bool isMinimized = WindowScope.isMinimizedOf(context); + expect(isMinimized, equals(false)); + return const SizedBox.shrink(); + }, + ), + ), + ); + }); + + testWidgets('Can access WindowScope.maybeIsMinimizedOf for regular windows', ( + WidgetTester tester, + ) async { + final _StubRegularWindowController controller = _StubRegularWindowController(tester); addTearDown(controller.dispose); await tester.pumpWidget( wrapWithView: false, @@ -300,8 +564,30 @@ void main() { ); }); - testWidgets('Can access WindowScope.isMaximizedOf', (WidgetTester tester) async { - final _StubWindowController controller = _StubWindowController(tester); + testWidgets('Can access WindowScope.maybeIsMinimizedOf for dialog windows', ( + WidgetTester tester, + ) async { + final _StubDialogWindowController controller = _StubDialogWindowController(tester); + addTearDown(controller.dispose); + await tester.pumpWidget( + wrapWithView: false, + DialogWindow( + controller: controller, + child: Builder( + builder: (BuildContext context) { + final bool? isMinimized = WindowScope.maybeIsMinimizedOf(context); + expect(isMinimized, equals(false)); + return const SizedBox.shrink(); + }, + ), + ), + ); + }); + + testWidgets('Can access WindowScope.isMaximizedOf for regular windows', ( + WidgetTester tester, + ) async { + final _StubRegularWindowController controller = _StubRegularWindowController(tester); addTearDown(controller.dispose); await tester.pumpWidget( wrapWithView: false, @@ -318,8 +604,30 @@ void main() { ); }); - testWidgets('Can access WindowScope.maybeIsMaximizedOf', (WidgetTester tester) async { - final _StubWindowController controller = _StubWindowController(tester); + testWidgets('Can access WindowScope.isMaximizedOf for dialog windows', ( + WidgetTester tester, + ) async { + final _StubDialogWindowController controller = _StubDialogWindowController(tester); + addTearDown(controller.dispose); + await tester.pumpWidget( + wrapWithView: false, + DialogWindow( + controller: controller, + child: Builder( + builder: (BuildContext context) { + final bool isMaximized = WindowScope.isMaximizedOf(context); + expect(isMaximized, equals(false)); + return const SizedBox.shrink(); + }, + ), + ), + ); + }); + + testWidgets('Can access WindowScope.maybeIsMaximizedOf for regular windows', ( + WidgetTester tester, + ) async { + final _StubRegularWindowController controller = _StubRegularWindowController(tester); addTearDown(controller.dispose); await tester.pumpWidget( wrapWithView: false, @@ -336,8 +644,30 @@ void main() { ); }); - testWidgets('Can access WindowScope.isFullscreenOf', (WidgetTester tester) async { - final _StubWindowController controller = _StubWindowController(tester); + testWidgets('Can access WindowScope.maybeIsMaximizedOf for dialog windows', ( + WidgetTester tester, + ) async { + final _StubDialogWindowController controller = _StubDialogWindowController(tester); + addTearDown(controller.dispose); + await tester.pumpWidget( + wrapWithView: false, + DialogWindow( + controller: controller, + child: Builder( + builder: (BuildContext context) { + final bool? isMaximized = WindowScope.maybeIsMaximizedOf(context); + expect(isMaximized, equals(false)); + return const SizedBox.shrink(); + }, + ), + ), + ); + }); + + testWidgets('Can access WindowScope.isFullscreenOf for regular windows', ( + WidgetTester tester, + ) async { + final _StubRegularWindowController controller = _StubRegularWindowController(tester); addTearDown(controller.dispose); await tester.pumpWidget( wrapWithView: false, @@ -354,8 +684,30 @@ void main() { ); }); - testWidgets('Can access WindowScope.maybeIsFullscreenOf', (WidgetTester tester) async { - final _StubWindowController controller = _StubWindowController(tester); + testWidgets('Can access WindowScope.isFullscreenOf for dialog windows', ( + WidgetTester tester, + ) async { + final _StubDialogWindowController controller = _StubDialogWindowController(tester); + addTearDown(controller.dispose); + await tester.pumpWidget( + wrapWithView: false, + DialogWindow( + controller: controller, + child: Builder( + builder: (BuildContext context) { + final bool isFullscreen = WindowScope.isFullscreenOf(context); + expect(isFullscreen, equals(false)); + return const SizedBox.shrink(); + }, + ), + ), + ); + }); + + testWidgets('Can access WindowScope.maybeIsFullscreenOf for regular windows', ( + WidgetTester tester, + ) async { + final _StubRegularWindowController controller = _StubRegularWindowController(tester); addTearDown(controller.dispose); await tester.pumpWidget( wrapWithView: false, @@ -371,6 +723,26 @@ void main() { ), ); }); + + testWidgets('Can access WindowScope.maybeIsFullscreenOf for dialog windows', ( + WidgetTester tester, + ) async { + final _StubDialogWindowController controller = _StubDialogWindowController(tester); + addTearDown(controller.dispose); + await tester.pumpWidget( + wrapWithView: false, + DialogWindow( + controller: controller, + child: Builder( + builder: (BuildContext context) { + final bool? isFullscreen = WindowScope.maybeIsFullscreenOf(context); + expect(isFullscreen, equals(false)); + return const SizedBox.shrink(); + }, + ), + ), + ); + }); }); }); } diff --git a/packages/flutter_test/lib/src/accessibility.dart b/packages/flutter_test/lib/src/accessibility.dart index 285279d3804..1a5552752e9 100644 --- a/packages/flutter_test/lib/src/accessibility.dart +++ b/packages/flutter_test/lib/src/accessibility.dart @@ -163,7 +163,7 @@ class MinimumTapTargetGuideline extends AccessibilityGuideline { } // skip node if it is touching the edge scrollable, since it might // be partially scrolled offscreen. - if (current.hasFlag(SemanticsFlag.hasImplicitScrolling) && + if (current.flagsCollection.hasImplicitScrolling && _isAtBoundary(paintBounds, current.rect)) { return result; } @@ -207,11 +207,11 @@ class MinimumTapTargetGuideline extends AccessibilityGuideline { // Skip node if it has no actions, or is marked as hidden. if ((!data.hasAction(ui.SemanticsAction.longPress) && !data.hasAction(ui.SemanticsAction.tap)) || - data.hasFlag(ui.SemanticsFlag.isHidden)) { + data.flagsCollection.isHidden) { return true; } // Skip links https://www.w3.org/WAI/WCAG21/Understanding/target-size.html - if (data.hasFlag(ui.SemanticsFlag.isLink)) { + if (data.flagsCollection.isLink) { return true; } return false; @@ -253,8 +253,8 @@ class LabeledTapTargetGuideline extends AccessibilityGuideline { }); if (node.isMergedIntoParent || node.isInvisible || - node.hasFlag(ui.SemanticsFlag.isHidden) || - node.hasFlag(ui.SemanticsFlag.isTextField)) { + node.flagsCollection.isHidden || + node.flagsCollection.isTextField) { return result; } final SemanticsData data = node.getSemanticsData(); @@ -346,12 +346,11 @@ class MinimumTextContrastGuideline extends AccessibilityGuideline { Evaluation result = const Evaluation.pass(); // Skip disabled nodes, as they not required to pass contrast check. - final bool isDisabled = - node.hasFlag(ui.SemanticsFlag.hasEnabledState) && !node.hasFlag(ui.SemanticsFlag.isEnabled); + final bool isDisabled = node.flagsCollection.isEnabled == ui.Tristate.isFalse; if (node.isInvisible || node.isMergedIntoParent || - node.hasFlag(ui.SemanticsFlag.isHidden) || + node.flagsCollection.isHidden || isDisabled) { return result; } @@ -481,8 +480,7 @@ class MinimumTextContrastGuideline extends AccessibilityGuideline { /// /// Skip routes which might have labels, and nodes without any text. bool shouldSkipNode(SemanticsData data) => - data.hasFlag(ui.SemanticsFlag.scopesRoute) || - (data.label.trim().isEmpty && data.value.trim().isEmpty); + data.flagsCollection.scopesRoute || (data.label.trim().isEmpty && data.value.trim().isEmpty); /// Returns if a rectangle of node is off the screen. /// diff --git a/packages/flutter_test/lib/src/controller.dart b/packages/flutter_test/lib/src/controller.dart index 9d54f05a71a..413db05458d 100644 --- a/packages/flutter_test/lib/src/controller.dart +++ b/packages/flutter_test/lib/src/controller.dart @@ -13,6 +13,7 @@ /// @docImport 'widget_tester.dart'; library; +import 'dart:ui' as ui; import 'package:clock/clock.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; @@ -74,17 +75,6 @@ class SemanticsController { SemanticsAction.scrollRight.index | SemanticsAction.scrollToOffset.index; - /// Based on Android's FOCUSABLE_FLAGS. See [flutter/engine/AccessibilityBridge.java](https://github.com/flutter/flutter/blob/main/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java). - static final int _importantFlagsForAccessibility = - SemanticsFlag.hasCheckedState.index | - SemanticsFlag.hasToggledState.index | - SemanticsFlag.hasEnabledState.index | - SemanticsFlag.isButton.index | - SemanticsFlag.isTextField.index | - SemanticsFlag.isFocusable.index | - SemanticsFlag.isSlider.index | - SemanticsFlag.isInMutuallyExclusiveGroup.index; - final WidgetController _controller; /// Attempts to find the [SemanticsNode] of first result from `finder`. @@ -353,7 +343,7 @@ class SemanticsController { final SemanticsData data = node.getSemanticsData(); // If the node scopes a route, it doesn't matter what other flags/actions it // has, it is _not_ important for accessibility, so we short circuit. - if (data.hasFlag(SemanticsFlag.scopesRoute)) { + if (data.flagsCollection.scopesRoute) { return false; } @@ -362,7 +352,17 @@ class SemanticsController { return true; } - final bool hasImportantFlag = data.flags & _importantFlagsForAccessibility != 0; + /// Based on Android's FOCUSABLE_FLAGS. See [flutter/engine/AccessibilityBridge.java](https://github.com/flutter/flutter/blob/main/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java). + final bool hasImportantFlag = + data.flagsCollection.isChecked != ui.CheckedState.none || + data.flagsCollection.isToggled != ui.Tristate.none || + data.flagsCollection.isEnabled != ui.Tristate.none || + data.flagsCollection.isButton || + data.flagsCollection.isTextField || + data.flagsCollection.isFocused != ui.Tristate.none || + data.flagsCollection.isSlider || + data.flagsCollection.isInMutuallyExclusiveGroup; + if (hasImportantFlag) { return true; } diff --git a/packages/flutter_test/lib/src/finders.dart b/packages/flutter_test/lib/src/finders.dart index 8ec1c8b9c2d..be9c9df3e98 100644 --- a/packages/flutter_test/lib/src/finders.dart +++ b/packages/flutter_test/lib/src/finders.dart @@ -1351,7 +1351,7 @@ class _FirstWidgetFinder extends ChainedFinder with _FirstFinderMixin { mixin _LastFinderMixin on ChainedFinderMixin { @override String describeMatch(Plurality plurality) { - return '${parent.describeMatch(plurality)} (ignoring all but first)'; + return '${parent.describeMatch(plurality)} (ignoring all but last)'; } @override diff --git a/packages/flutter_test/lib/src/matchers.dart b/packages/flutter_test/lib/src/matchers.dart index 2fb1f571b24..8d5444c2209 100644 --- a/packages/flutter_test/lib/src/matchers.dart +++ b/packages/flutter_test/lib/src/matchers.dart @@ -2454,38 +2454,38 @@ class _MatchesSemanticsData extends Matcher { required String? onLongPressHint, required this.customActions, required this.children, - }) : flags = { - SemanticsFlag.hasCheckedState: ?hasCheckedState, - SemanticsFlag.isChecked: ?isChecked, - SemanticsFlag.isCheckStateMixed: ?isCheckStateMixed, - SemanticsFlag.isSelected: ?isSelected, - SemanticsFlag.hasSelectedState: ?hasSelectedState, - SemanticsFlag.isButton: ?isButton, - SemanticsFlag.isSlider: ?isSlider, - SemanticsFlag.isKeyboardKey: ?isKeyboardKey, - SemanticsFlag.isLink: ?isLink, - SemanticsFlag.isTextField: ?isTextField, - SemanticsFlag.isReadOnly: ?isReadOnly, - SemanticsFlag.isFocused: ?isFocused, - SemanticsFlag.isFocusable: ?isFocusable, - SemanticsFlag.hasEnabledState: ?hasEnabledState, - SemanticsFlag.isEnabled: ?isEnabled, - SemanticsFlag.isInMutuallyExclusiveGroup: ?isInMutuallyExclusiveGroup, - SemanticsFlag.isHeader: ?isHeader, - SemanticsFlag.isObscured: ?isObscured, - SemanticsFlag.isMultiline: ?isMultiline, - SemanticsFlag.namesRoute: ?namesRoute, - SemanticsFlag.scopesRoute: ?scopesRoute, - SemanticsFlag.isHidden: ?isHidden, - SemanticsFlag.isImage: ?isImage, - SemanticsFlag.isLiveRegion: ?isLiveRegion, - SemanticsFlag.hasToggledState: ?hasToggledState, - SemanticsFlag.isToggled: ?isToggled, - SemanticsFlag.hasImplicitScrolling: ?hasImplicitScrolling, - SemanticsFlag.hasExpandedState: ?hasExpandedState, - SemanticsFlag.isExpanded: ?isExpanded, - SemanticsFlag.hasRequiredState: ?hasRequiredState, - SemanticsFlag.isRequired: ?isRequired, + }) : flags = { + 'hasCheckedState': ?hasCheckedState, + 'isChecked': ?isChecked, + 'isCheckStateMixed': ?isCheckStateMixed, + 'isSelected': ?isSelected, + 'hasSelectedState': ?hasSelectedState, + 'isButton': ?isButton, + 'isSlider': ?isSlider, + 'isKeyboardKey': ?isKeyboardKey, + 'isLink': ?isLink, + 'isTextField': ?isTextField, + 'isReadOnly': ?isReadOnly, + 'isFocused': ?isFocused, + 'isFocusable': ?isFocusable, + 'hasEnabledState': ?hasEnabledState, + 'isEnabled': ?isEnabled, + 'isInMutuallyExclusiveGroup': ?isInMutuallyExclusiveGroup, + 'isHeader': ?isHeader, + 'isObscured': ?isObscured, + 'isMultiline': ?isMultiline, + 'namesRoute': ?namesRoute, + 'scopesRoute': ?scopesRoute, + 'isHidden': ?isHidden, + 'isImage': ?isImage, + 'isLiveRegion': ?isLiveRegion, + 'hasToggledState': ?hasToggledState, + 'isToggled': ?isToggled, + 'hasImplicitScrolling': ?hasImplicitScrolling, + 'hasExpandedState': ?hasExpandedState, + 'isExpanded': ?isExpanded, + 'hasRequiredState': ?hasRequiredState, + 'isRequired': ?isRequired, }, actions = { SemanticsAction.tap: ?hasTapAction, @@ -2546,7 +2546,7 @@ class _MatchesSemanticsData extends Matcher { /// 2. If the flag/action maps to `false`, then it must not be present in the SemanticData /// 3. If the flag/action is not in the map, then it will not be validated against final Map actions; - final Map flags; + final Map flags; @override Description describe(Description description, [String? index]) { @@ -2598,27 +2598,27 @@ class _MatchesSemanticsData extends Matcher { .toList(); if (expectedActions.isNotEmpty) { - description.add(' with actions: ${_createEnumsSummary(expectedActions)} '); + description.add(' with actions: ${_createSemanticsActionSummary(expectedActions)} '); } if (notExpectedActions.isNotEmpty) { - description.add(' without actions: ${_createEnumsSummary(notExpectedActions)} '); + description.add(' without actions: ${_createSemanticsActionSummary(notExpectedActions)} '); } } if (flags.isNotEmpty) { - final List expectedFlags = flags.entries - .where((MapEntry e) => e.value) - .map((MapEntry e) => e.key) + final List expectedFlags = flags.entries + .where((MapEntry e) => e.value) + .map((MapEntry e) => e.key) .toList(); - final List notExpectedFlags = flags.entries - .where((MapEntry e) => !e.value) - .map((MapEntry e) => e.key) + final List notExpectedFlags = flags.entries + .where((MapEntry e) => !e.value) + .map((MapEntry e) => e.key) .toList(); if (expectedFlags.isNotEmpty) { - description.add(' with flags: ${_createEnumsSummary(expectedFlags)} '); + description.add(' with flags: ${expectedFlags.join(',')} '); } if (notExpectedFlags.isNotEmpty) { - description.add(' without flags: ${_createEnumsSummary(notExpectedFlags)} '); + description.add(' without flags: ${notExpectedFlags.join(', ')} '); } } if (textDirection != null) { @@ -2803,7 +2803,7 @@ class _MatchesSemanticsData extends Matcher { if (unexpectedActions.isNotEmpty || missingActions.isNotEmpty) { return failWithDescription( matchState, - 'missing actions: ${_createEnumsSummary(missingActions)} unexpected actions: ${_createEnumsSummary(unexpectedActions)}', + 'missing actions: ${_createSemanticsActionSummary(missingActions)} unexpected actions: ${_createSemanticsActionSummary(unexpectedActions)}', ); } } @@ -2848,17 +2848,18 @@ class _MatchesSemanticsData extends Matcher { } } if (flags.isNotEmpty) { - final List unexpectedFlags = []; - final List missingFlags = []; - for (final MapEntry flagEntry in flags.entries) { - final ui.SemanticsFlag flag = flagEntry.key; + final Map foundFlags = _stringsMapFromSemanticsFlags(data.flagsCollection); + final List unexpectedFlags = []; + final List missingFlags = []; + for (final MapEntry flagEntry in flags.entries) { + final String flagName = flagEntry.key; final bool flagExpected = flagEntry.value; - final bool flagPresent = flag.index & data.flags == flag.index; + final bool flagPresent = foundFlags[flagName]!; if (flagPresent != flagExpected) { if (flagExpected) { - missingFlags.add(flag); + missingFlags.add(flagName); } else { - unexpectedFlags.add(flag); + unexpectedFlags.add(flagName); } } } @@ -2866,7 +2867,7 @@ class _MatchesSemanticsData extends Matcher { if (unexpectedFlags.isNotEmpty || missingFlags.isNotEmpty) { return failWithDescription( matchState, - 'missing flags: ${_createEnumsSummary(missingFlags)} unexpected flags: ${_createEnumsSummary(unexpectedFlags)}', + 'missing flags: ${missingFlags.join(',')} unexpected flags: ${unexpectedFlags.join(',')}', ); } } @@ -2897,16 +2898,8 @@ class _MatchesSemanticsData extends Matcher { return mismatchDescription.add(matchState['failure'] as String); } - static String _createEnumsSummary(List enums) { - assert( - T == SemanticsAction || T == SemanticsFlag, - 'This method is only intended for lists of SemanticsActions or SemanticsFlags.', - ); - if (T == SemanticsAction) { - return '[${(enums as List).map((SemanticsAction d) => d.name).join(', ')}]'; - } else { - return '[${(enums as List).map((SemanticsFlag d) => d.name).join(', ')}]'; - } + static String _createSemanticsActionSummary(List enums) { + return '[${enums.map((ui.SemanticsAction d) => d.name).join(', ')}]'; } } @@ -2949,3 +2942,39 @@ class _DoesNotMatchAccessibilityGuideline extends AsyncMatcher { return null; } } + +Map _stringsMapFromSemanticsFlags(SemanticsFlags flagsCollection) { + return { + 'hasCheckedState': flagsCollection.isChecked != ui.CheckedState.none, + 'isChecked': flagsCollection.isChecked == ui.CheckedState.isTrue, + 'isCheckStateMixed': flagsCollection.isChecked == ui.CheckedState.mixed, + 'isSelected': flagsCollection.isSelected == ui.Tristate.isTrue, + 'hasSelectedState': flagsCollection.isSelected != ui.Tristate.none, + 'isButton': flagsCollection.isButton, + 'isSlider': flagsCollection.isSlider, + 'isKeyboardKey': flagsCollection.isKeyboardKey, + 'isLink': flagsCollection.isLink, + 'isFocused': flagsCollection.isFocused == ui.Tristate.isTrue, + 'isFocusable': flagsCollection.isFocused != ui.Tristate.none, + 'isTextField': flagsCollection.isTextField, + 'isReadOnly': flagsCollection.isReadOnly, + 'hasEnabledState': flagsCollection.isEnabled != ui.Tristate.none, + 'isEnabled': flagsCollection.isEnabled == ui.Tristate.isTrue, + 'isInMutuallyExclusiveGroup': flagsCollection.isInMutuallyExclusiveGroup, + 'isHeader': flagsCollection.isHeader, + 'isObscured': flagsCollection.isObscured, + 'isMultiline': flagsCollection.isMultiline, + 'namesRoute': flagsCollection.namesRoute, + 'scopesRoute': flagsCollection.scopesRoute, + 'isHidden': flagsCollection.isHidden, + 'isImage': flagsCollection.isImage, + 'isLiveRegion': flagsCollection.isLiveRegion, + 'hasToggledState': flagsCollection.isToggled != ui.Tristate.none, + 'isToggled': flagsCollection.isToggled == ui.Tristate.isTrue, + 'hasImplicitScrolling': flagsCollection.hasImplicitScrolling, + 'hasExpandedState': flagsCollection.isExpanded != ui.Tristate.none, + 'isExpanded': flagsCollection.isExpanded == ui.Tristate.isTrue, + 'hasRequiredState': flagsCollection.isRequired != ui.Tristate.none, + 'isRequired': flagsCollection.isRequired == ui.Tristate.isTrue, + }; +} diff --git a/packages/flutter_test/lib/src/window.dart b/packages/flutter_test/lib/src/window.dart index 78e7af53eb5..17ddfbc051d 100644 --- a/packages/flutter_test/lib/src/window.dart +++ b/packages/flutter_test/lib/src/window.dart @@ -484,6 +484,14 @@ class TestPlatformDispatcher implements PlatformDispatcher { bool get semanticsEnabled => _semanticsEnabledTestValue ?? _platformDispatcher.semanticsEnabled; bool? _semanticsEnabledTestValue; + /// The application locale set during the test. + Locale? applicationLocale; + + @override + void setApplicationLocale(Locale locale) { + applicationLocale = locale; + } + /// Hides the real semantics enabled and reports the given /// [semanticsEnabledTestValue] instead. // ignore: avoid_setters_without_getters diff --git a/packages/flutter_test/test/finders_test.dart b/packages/flutter_test/test/finders_test.dart index ff7c61f9626..280a95d9cfd 100644 --- a/packages/flutter_test/test/finders_test.dart +++ b/packages/flutter_test/test/finders_test.dart @@ -1655,6 +1655,18 @@ void main() { expect(finder.found, orderedEquals(expected)); }); }); + + group('first and last', () { + test('describes first correctly', () { + final _FakeFinder finder = _FakeFinder(); + expect(finder.first.toString(describeSelf: true), contains('(ignoring all but first)')); + }); + + test('describes last correctly', () { + final _FakeFinder finder = _FakeFinder(); + expect(finder.last.toString(describeSelf: true), contains('(ignoring all but last)')); + }); + }); }); } diff --git a/packages/flutter_tools/gradle/src/main/kotlin/DependencyVersionChecker.kt b/packages/flutter_tools/gradle/src/main/kotlin/DependencyVersionChecker.kt index 2227f7c1fc0..2482f9862b9 100644 --- a/packages/flutter_tools/gradle/src/main/kotlin/DependencyVersionChecker.kt +++ b/packages/flutter_tools/gradle/src/main/kotlin/DependencyVersionChecker.kt @@ -97,7 +97,7 @@ object DependencyVersionChecker { // Java error and warn should align with packages/flutter_tools/lib/src/android/gradle_utils.dart. @VisibleForTesting internal val warnJavaVersion: JavaVersion = JavaVersion.VERSION_17 - @VisibleForTesting internal val errorJavaVersion: JavaVersion = JavaVersion.VERSION_11 + @VisibleForTesting internal val errorJavaVersion: JavaVersion = JavaVersion.VERSION_17 @VisibleForTesting internal val warnAGPVersion: AndroidPluginVersion = AndroidPluginVersion(8, 6, 0) diff --git a/packages/flutter_tools/gradle/src/test/kotlin/DependencyVersionCheckerTest.kt b/packages/flutter_tools/gradle/src/test/kotlin/DependencyVersionCheckerTest.kt index ed7fade0095..b4807229bfd 100644 --- a/packages/flutter_tools/gradle/src/test/kotlin/DependencyVersionCheckerTest.kt +++ b/packages/flutter_tools/gradle/src/test/kotlin/DependencyVersionCheckerTest.kt @@ -16,6 +16,7 @@ import com.flutter.gradle.DependencyVersionChecker.OUT_OF_SUPPORT_RANGE_PROPERTY import com.flutter.gradle.DependencyVersionChecker.POTENTIAL_JAVA_FIX import com.flutter.gradle.DependencyVersionChecker.errorAGPVersion import com.flutter.gradle.DependencyVersionChecker.errorGradleVersion +import com.flutter.gradle.DependencyVersionChecker.errorJavaVersion import com.flutter.gradle.DependencyVersionChecker.errorKGPVersion import com.flutter.gradle.DependencyVersionChecker.errorMinSdkVersion import com.flutter.gradle.DependencyVersionChecker.getErrorMessage @@ -27,7 +28,6 @@ import com.flutter.gradle.DependencyVersionChecker.getPotentialSDKFix import com.flutter.gradle.DependencyVersionChecker.getWarnMessage import com.flutter.gradle.DependencyVersionChecker.warnAGPVersion import com.flutter.gradle.DependencyVersionChecker.warnGradleVersion -import com.flutter.gradle.DependencyVersionChecker.warnJavaVersion import com.flutter.gradle.DependencyVersionChecker.warnKGPVersion import com.flutter.gradle.DependencyVersionChecker.warnMinSdkVersion import io.mockk.every @@ -154,31 +154,31 @@ class DependencyVersionCheckerTest { verify(exactly = 0) { mockExtraPropertiesExtension.set(OUT_OF_SUPPORT_RANGE_PROPERTY, true) } } - // No test for Java version in error range, as the lowest supported Java version is also the + // No test for Java version in warn range, as the lowest supported Java version is also the // lowest possible. - @Test - fun `Java version in warn range results in warning logs`() { - val exampleWarnJavaVersion = JavaVersion.VERSION_16 - val mockProject = MockProjectFactory.createMockProjectWithSpecifiedDependencyVersions(javaVersion = exampleWarnJavaVersion) + fun `Java version in error range results in error logs`() { + val exampleErrorJavaVersion = JavaVersion.VERSION_16 + val mockProject = MockProjectFactory.createMockProjectWithSpecifiedDependencyVersions(javaVersion = exampleErrorJavaVersion) val mockExtraPropertiesExtension = mockProject.extra every { mockExtraPropertiesExtension.set(OUT_OF_SUPPORT_RANGE_PROPERTY, false) } returns Unit + every { mockExtraPropertiesExtension.set(OUT_OF_SUPPORT_RANGE_PROPERTY, true) } returns Unit val mockLogger = mockProject.logger every { mockLogger.error(any()) } returns Unit - DependencyVersionChecker.checkDependencyVersions(mockProject) - verify { - mockLogger.error( - getWarnMessage( + val dependencyValidationException = + assertFailsWith { DependencyVersionChecker.checkDependencyVersions(mockProject) } + assert( + dependencyValidationException.message == + getErrorMessage( JAVA_NAME, - exampleWarnJavaVersion.toString(), - warnJavaVersion.toString(), + exampleErrorJavaVersion.toString(), + errorJavaVersion.toString(), POTENTIAL_JAVA_FIX ) - ) - } - verify(exactly = 0) { mockExtraPropertiesExtension.set(OUT_OF_SUPPORT_RANGE_PROPERTY, true) } + ) + verify(exactly = 1) { mockExtraPropertiesExtension.set(OUT_OF_SUPPORT_RANGE_PROPERTY, true) } } @Test diff --git a/packages/flutter_tools/lib/src/android/gradle_utils.dart b/packages/flutter_tools/lib/src/android/gradle_utils.dart index 4e158b4d534..14b3245aa5b 100644 --- a/packages/flutter_tools/lib/src/android/gradle_utils.dart +++ b/packages/flutter_tools/lib/src/android/gradle_utils.dart @@ -59,7 +59,7 @@ const targetSdkVersion = '36'; const ndkVersion = '27.0.12077973'; final minBuildToolsVersion = Version(28, 0, 3); // Align with packages/flutter_tools/gradle/src/main/kotlin/DependencyVersionChecker.kt. -final errorJavaMinVersionAndroid = Version(11, 0, 0); +final errorJavaMinVersionAndroid = Version(17, 0, 0); final warnJavaMinVersionAndroid = Version(17, 0, 0); // Update these when new major versions of Java are supported by new Gradle diff --git a/packages/flutter_tools/lib/src/commands/widget_preview.dart b/packages/flutter_tools/lib/src/commands/widget_preview.dart index e6c509658a5..8452657df2b 100644 --- a/packages/flutter_tools/lib/src/commands/widget_preview.dart +++ b/packages/flutter_tools/lib/src/commands/widget_preview.dart @@ -448,6 +448,7 @@ final class WidgetPreviewStartCommand extends WidgetPreviewSubCommandBase with C widgetPreviewScaffoldProject.packageConfig.readAsBytesSync(), widgetPreviewScaffoldProject.packageConfig.uri, ), + trackWidgetCreation: true, // Don't try and download canvaskit from the CDN. useLocalCanvasKit: true, webEnableHotReload: true, diff --git a/packages/flutter_tools/lib/src/features.dart b/packages/flutter_tools/lib/src/features.dart index 74fb5da826b..c375078c4df 100644 --- a/packages/flutter_tools/lib/src/features.dart +++ b/packages/flutter_tools/lib/src/features.dart @@ -188,6 +188,7 @@ const nativeAssets = Feature( environmentOverride: 'FLUTTER_NATIVE_ASSETS', master: FeatureChannelSetting(available: true, enabledByDefault: true), beta: FeatureChannelSetting(available: true, enabledByDefault: true), + stable: FeatureChannelSetting(available: true, enabledByDefault: true), ); /// Enable Dart data assets building and bundling. diff --git a/packages/flutter_tools/lib/src/resident_runner.dart b/packages/flutter_tools/lib/src/resident_runner.dart index ed44be71db9..534cfc22a89 100644 --- a/packages/flutter_tools/lib/src/resident_runner.dart +++ b/packages/flutter_tools/lib/src/resident_runner.dart @@ -1468,11 +1468,11 @@ abstract class ResidentRunner extends ResidentHandlers { /// of the default URI encoding. String urlToDisplayString(Uri uri) { final base = StringBuffer(uri.withoutQueryParameters().toString()); - base.write( - uri.queryParameters.keys - .map((String key) => '$key=${uri.queryParameters[key]}') - .join('&'), - ); + if (uri.hasQuery) { + base.write( + '?${uri.queryParameters.keys.map((String key) => '$key=${uri.queryParameters[key]}').join('&')}', + ); + } return base.toString(); } diff --git a/packages/flutter_tools/lib/src/update_packages_pins.dart b/packages/flutter_tools/lib/src/update_packages_pins.dart index 9615e1522c5..d0d5123cb3d 100644 --- a/packages/flutter_tools/lib/src/update_packages_pins.dart +++ b/packages/flutter_tools/lib/src/update_packages_pins.dart @@ -22,7 +22,7 @@ const kManuallyPinnedDependencies = { // Add pinned packages here. Please leave a comment explaining why. 'archive': '3.6.1', // https://github.com/flutter/flutter/issues/115660 'code_assets': - '0.19.6', // Under active development with breaking changes until 1.0.0. Manually rolled by @dcharkes. + '0.19.7', // Under active development with breaking changes until 1.0.0. Manually rolled by @dcharkes. 'dds': '5.0.3', // 5.0.4 contains bugs described in https://github.com/Dart-Code/Dart-Code/issues/4678. 'flutter_gallery_assets': '1.0.2', // Tests depend on the exact version. @@ -31,7 +31,7 @@ const kManuallyPinnedDependencies = { 'hooks': '0.20.1', // Under active development with breaking changes until 1.0.0. Manually rolled by @dcharkes. 'hooks_runner': - '0.22.1', // Under active development with breaking changes until 1.0.0. Manually rolled by @dcharkes. + '0.23.0', // Under active development with breaking changes until 1.0.0. Manually rolled by @dcharkes. 'material_color_utilities': '0.11.1', // Keep pinned to latest until 1.0.0. }; diff --git a/packages/flutter_tools/lib/src/widget_preview/dependency_graph.dart b/packages/flutter_tools/lib/src/widget_preview/dependency_graph.dart index 278e52c308b..69d8950e664 100644 --- a/packages/flutter_tools/lib/src/widget_preview/dependency_graph.dart +++ b/packages/flutter_tools/lib/src/widget_preview/dependency_graph.dart @@ -11,9 +11,9 @@ import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/constant/value.dart'; -import 'package:analyzer/dart/element/element2.dart'; +import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/diagnostic/diagnostic.dart'; -import 'package:analyzer/error/error.dart'; +import 'package:analyzer/source/line_info.dart'; import '../base/logger.dart'; import 'preview_details.dart'; @@ -33,7 +33,7 @@ typedef PreviewDependencyGraph = Map; /// Visitor which detects previews and extracts [PreviewDetails] for later code /// generation. class _PreviewVisitor extends RecursiveAstVisitor { - _PreviewVisitor({required LibraryElement2 lib}) + _PreviewVisitor({required LibraryElement lib}) : packageName = lib.uri.scheme == 'package' ? lib.uri.pathSegments.first : null; late final String? packageName; @@ -45,9 +45,12 @@ class _PreviewVisitor extends RecursiveAstVisitor { MethodDeclaration? _currentMethod; late Uri _currentScriptUri; + late CompilationUnit _currentUnit; void findPreviewsInResolvedUnitResult(ResolvedUnitResult unit) { - _scopedVisitChildren(unit.unit, (_) => _currentScriptUri = unit.file.toUri()); + _currentScriptUri = unit.file.toUri(); + _currentUnit = unit.unit; + _currentUnit.visitChildren(this); } /// Handles previews defined on top-level functions. @@ -96,6 +99,10 @@ class _PreviewVisitor extends RecursiveAstVisitor { if (preview == null) { return; } + final LineInfo lineInfo = _currentUnit.lineInfo; + final CharacterLocation location = lineInfo.getLocation(node.offset); + final int line = location.lineNumber; + final int column = location.columnNumber; if (_currentFunction != null && !hasRequiredParams(_currentFunction!.functionExpression.parameters)) { final TypeAnnotation? returnTypeAnnotation = _currentFunction!.returnType; @@ -105,6 +112,8 @@ class _PreviewVisitor extends RecursiveAstVisitor { previewEntries.add( PreviewDetails( scriptUri: _currentScriptUri, + line: line, + column: column, packageName: packageName, functionName: _currentFunction!.name.toString(), isBuilder: returnType.isWidgetBuilder, @@ -120,6 +129,8 @@ class _PreviewVisitor extends RecursiveAstVisitor { previewEntries.add( PreviewDetails( scriptUri: _currentScriptUri, + line: line, + column: column, packageName: packageName, functionName: '$returnType${name == null ? '' : '.$name'}', isBuilder: false, @@ -136,6 +147,8 @@ class _PreviewVisitor extends RecursiveAstVisitor { previewEntries.add( PreviewDetails( scriptUri: _currentScriptUri, + line: line, + column: column, packageName: packageName, functionName: '${parentClass.name}.${_currentMethod!.name}', isBuilder: returnType.isWidgetBuilder, @@ -194,7 +207,7 @@ final class LibraryPreviewNode { bool get hasErrors => errors.isNotEmpty; /// The set of errors found in this library. - final errors = []; + final errors = []; /// Determines the set of errors found in this library. /// @@ -203,8 +216,8 @@ final class LibraryPreviewNode { errors.clear(); for (final String file in files) { errors.addAll( - ((await context.currentSession.getErrors(file)) as ErrorsResult).errors - .where((AnalysisError error) => error.severity == Severity.error) + ((await context.currentSession.getErrors(file)) as ErrorsResult).diagnostics + .where((error) => error.severity == Severity.error) .toList(), ); } diff --git a/packages/flutter_tools/lib/src/widget_preview/preview_code_generator.dart b/packages/flutter_tools/lib/src/widget_preview/preview_code_generator.dart index 29244214dd7..104306a7744 100644 --- a/packages/flutter_tools/lib/src/widget_preview/preview_code_generator.dart +++ b/packages/flutter_tools/lib/src/widget_preview/preview_code_generator.dart @@ -3,8 +3,8 @@ // found in the LICENSE file. import 'package:analyzer/dart/constant/value.dart'; -import 'package:analyzer/dart/element/element2.dart' as analyzer; -import 'package:analyzer/dart/element/element2.dart'; +import 'package:analyzer/dart/element/element.dart' as analyzer; +import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:built_collection/built_collection.dart'; import 'package:code_builder/code_builder.dart' as cb; @@ -32,7 +32,9 @@ class PreviewCodeGenerator { static const _kBuildMultiWidgetPreview = 'buildMultiWidgetPreview'; static const _kBuildWidgetPreview = 'buildWidgetPreview'; static const _kBuildWidgetPreviewError = 'buildWidgetPreviewError'; + static const _kColumn = 'column'; static const _kDependencyHasErrors = 'dependencyHasErrors'; + static const _kLine = 'line'; static const _kListType = 'List'; static const _kPackageName = 'packageName'; static const _kPackageUri = 'packageUri'; @@ -164,6 +166,8 @@ class PreviewCodeGenerator { final args = { _kPackageName: cb.literalString(preview.packageName!), _kScriptUri: cb.literalString(preview.scriptUri.toString()), + _kLine: cb.literalNum(preview.line), + _kColumn: cb.literalNum(preview.column), }; // TODO(bkonyi): improve the error related code. if (libraryDetails.hasErrors || libraryDetails.dependencyHasErrors) { @@ -206,7 +210,7 @@ extension on DartObject { DartType(isDartCoreInt: true) => cb.literalNum(toIntValue()!), DartType(isDartCoreString: true) => cb.literalString(toStringValue()!), DartType(isDartCoreNull: true) => cb.literalNull, - InterfaceType(element3: EnumElement()) => _createEnumInstance(this), + InterfaceType(element: EnumElement()) => _createEnumInstance(this), InterfaceType() => _createInstance(type, this), FunctionType() => _createTearoff(toFunctionValue()!), _ => throw UnsupportedError('Unexpected DartObject type: $runtimeType'), @@ -238,10 +242,10 @@ extension on DartObject { final ConstructorInvocation constructorInvocation = object.constructorInvocation!; final ConstructorElement constructor = constructorInvocation.constructor; final cb.Expression type = cb.refer( - dartType.element3.name3!, - _elementToLibraryIdentifier(dartType.element3), + dartType.element.name!, + _elementToLibraryIdentifier(dartType.element), ); - final String? name = constructor.name3 == 'new' ? null : constructor.name3; + final String? name = constructor.name == 'new' ? null : constructor.name; final List positionalArguments = constructorInvocation.positionalArguments .map((e) => e.toExpression()) diff --git a/packages/flutter_tools/lib/src/widget_preview/preview_details.dart b/packages/flutter_tools/lib/src/widget_preview/preview_details.dart index 91b0bf0ad6f..733438af9ee 100644 --- a/packages/flutter_tools/lib/src/widget_preview/preview_details.dart +++ b/packages/flutter_tools/lib/src/widget_preview/preview_details.dart @@ -10,6 +10,8 @@ typedef PreviewProperty = ({String key, DartObject object, bool isCallback}); final class PreviewDetails { PreviewDetails({ required this.scriptUri, + required this.line, + required this.column, required this.packageName, required this.functionName, required this.isBuilder, @@ -20,6 +22,12 @@ final class PreviewDetails { /// The file:// URI pointing to the script in which the preview is defined. final Uri scriptUri; + /// The 1-based line at which the Preview annotation was applied. + final int line; + + /// The 1-based column at which the Preview annotation was applied. + final int column; + /// The name of the package in which the preview was defined. /// /// For example, if this preview is defined in 'package:foo/src/bar.dart', this diff --git a/packages/flutter_tools/lib/src/widget_preview/utils.dart b/packages/flutter_tools/lib/src/widget_preview/utils.dart index e0f6747b454..6b37a8904ca 100644 --- a/packages/flutter_tools/lib/src/widget_preview/utils.dart +++ b/packages/flutter_tools/lib/src/widget_preview/utils.dart @@ -8,7 +8,7 @@ import 'dart:collection'; import 'package:analyzer/dart/analysis/results.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; -import 'package:analyzer/dart/element/element2.dart'; +import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/source/source.dart'; import 'package:collection/collection.dart'; diff --git a/packages/flutter_tools/pubspec.yaml b/packages/flutter_tools/pubspec.yaml index 479b74552f6..fb669482f8a 100644 --- a/packages/flutter_tools/pubspec.yaml +++ b/packages/flutter_tools/pubspec.yaml @@ -58,9 +58,9 @@ dependencies: pubspec_parse: 1.5.0 graphs: 2.3.2 - hooks_runner: 0.22.1 + hooks_runner: 0.23.0 hooks: 0.20.1 - code_assets: 0.19.6 + code_assets: 0.19.7 data_assets: 0.19.3 # We depend on very specific internal implementation details of the @@ -127,4 +127,4 @@ dev_dependencies: dartdoc: # Exclude this package from the hosted API docs. nodoc: true -# PUBSPEC CHECKSUM: sro36f +# PUBSPEC CHECKSUM: 37t3vr diff --git a/packages/flutter_tools/templates/package_ffi/pubspec.yaml.tmpl b/packages/flutter_tools/templates/package_ffi/pubspec.yaml.tmpl index 935e47e8652..e616c27d1e9 100644 --- a/packages/flutter_tools/templates/package_ffi/pubspec.yaml.tmpl +++ b/packages/flutter_tools/templates/package_ffi/pubspec.yaml.tmpl @@ -6,7 +6,7 @@ environment: sdk: {{dartSdkVersionBounds}} dependencies: - code_assets: ^0.19.6 + code_assets: ^0.19.7 hooks: ^0.20.1 logging: ^1.3.0 native_toolchain_c: ^0.17.1 diff --git a/packages/flutter_tools/templates/widget_preview_scaffold/lib/src/utils.dart.tmpl b/packages/flutter_tools/templates/widget_preview_scaffold/lib/src/utils.dart.tmpl index f66c203e5b2..05d0bef7315 100644 --- a/packages/flutter_tools/templates/widget_preview_scaffold/lib/src/utils.dart.tmpl +++ b/packages/flutter_tools/templates/widget_preview_scaffold/lib/src/utils.dart.tmpl @@ -9,6 +9,8 @@ import 'package:widget_preview_scaffold/src/widget_preview.dart'; Iterable buildMultiWidgetPreview({ required String packageName, required String scriptUri, + required int line, + required int column, required MultiPreview preview, required Object? Function() previewFunction, }) { @@ -16,6 +18,8 @@ Iterable buildMultiWidgetPreview({ (p) => buildWidgetPreview( packageName: packageName, scriptUri: scriptUri, + line: line, + column: column, transformedPreview: p, previewFunction: previewFunction, ), @@ -25,6 +29,8 @@ Iterable buildMultiWidgetPreview({ WidgetPreview buildWidgetPreview({ required String packageName, required String scriptUri, + required int line, + required int column, required Preview transformedPreview, required Object? Function() previewFunction, }) { @@ -39,6 +45,8 @@ WidgetPreview buildWidgetPreview({ return WidgetPreview( builder: previewBuilder, scriptUri: scriptUri, + line: line, + column: column, previewData: transformedPreview, packageName: packageName, ); @@ -47,6 +55,8 @@ WidgetPreview buildWidgetPreview({ WidgetPreview buildWidgetPreviewError({ required String packageName, required String scriptUri, + required int line, + required int column, required String packageUri, required String functionName, required bool dependencyHasErrors, @@ -58,6 +68,8 @@ WidgetPreview buildWidgetPreviewError({ return WidgetPreview( builder: () => Text('$functionName: $errorMessage'), scriptUri: scriptUri, + line: line, + column: column, previewData: const Preview(group: 'Invalid Previews'), packageName: packageName, ); diff --git a/packages/flutter_tools/templates/widget_preview_scaffold/lib/src/widget_preview.dart.tmpl b/packages/flutter_tools/templates/widget_preview_scaffold/lib/src/widget_preview.dart.tmpl index 2c4af1eddf5..29be79b4769 100644 --- a/packages/flutter_tools/templates/widget_preview_scaffold/lib/src/widget_preview.dart.tmpl +++ b/packages/flutter_tools/templates/widget_preview_scaffold/lib/src/widget_preview.dart.tmpl @@ -31,15 +31,33 @@ class WidgetPreview { const WidgetPreview({ required this.builder, required this.scriptUri, + required this.line, + required this.column, required this.previewData, required this.packageName, }); + @visibleForTesting + const WidgetPreview.test({ + required this.builder, + required this.previewData, + this.scriptUri = '', + this.line = -1, + this.column = -1, + this.packageName = '', + }); + /// The absolute file:// URI pointing to the script containing this preview. /// /// This matches the URI format sent by IDEs for active location change events. final String scriptUri; + /// The line at which the Preview annotation was applied. + final int line; + + /// The column at which the Preview annotation was applied. + final int column; + /// The name of the package in which a preview was defined. /// /// For example, if a preview is defined in 'package:foo/src/bar.dart', this @@ -104,6 +122,7 @@ class WidgetPreview { void debugFillProperties(DiagnosticPropertiesBuilder properties) { properties ..add(DiagnosticsProperty('name', name, ifNull: 'not set')) + ..add(DiagnosticsProperty('group', previewData.group)) ..add(DiagnosticsProperty('size', size)) ..add(DiagnosticsProperty('textScaleFactor', textScaleFactor)) ..add(DiagnosticsProperty('theme', theme)) diff --git a/packages/flutter_tools/templates/widget_preview_scaffold/lib/src/widget_preview_rendering.dart.tmpl b/packages/flutter_tools/templates/widget_preview_scaffold/lib/src/widget_preview_rendering.dart.tmpl index 2549899543a..47faa6c5c10 100644 --- a/packages/flutter_tools/templates/widget_preview_scaffold/lib/src/widget_preview_rendering.dart.tmpl +++ b/packages/flutter_tools/templates/widget_preview_scaffold/lib/src/widget_preview_rendering.dart.tmpl @@ -178,12 +178,16 @@ class NoPreviewsDetectedWidget extends StatelessWidget { } } +/// A wrapper that serves as the root entry for a single preview in the widget inspector. class PreviewWidget extends StatelessWidget { const PreviewWidget({super.key, required this.preview, required this.child}); final WidgetPreview preview; final Widget child; + @override + StatelessElement createElement() => PreviewWidgetElement(this); + @override Widget build(BuildContext context) { return child; @@ -191,7 +195,9 @@ class PreviewWidget extends StatelessWidget { @override String toStringShort() { - final StringBuffer buffer = StringBuffer('@Preview'); + final StringBuffer buffer = StringBuffer( + '@${preview.previewData.runtimeType}', + ); if (preview.name != null) { buffer.write('(name: "${preview.name}")'); } @@ -205,6 +211,12 @@ class PreviewWidget extends StatelessWidget { } } +/// A custom [StatelessElement] with the sole purpose of simplifying identifying +/// selections of @Preview annotations in the widget inspector. +class PreviewWidgetElement extends StatelessElement { + PreviewWidgetElement(super.widget); +} + class WidgetPreviewGroupWidget extends StatelessWidget { const WidgetPreviewGroupWidget({ super.key, diff --git a/packages/flutter_tools/templates/widget_preview_scaffold/lib/src/widget_preview_scaffold_controller.dart.tmpl b/packages/flutter_tools/templates/widget_preview_scaffold/lib/src/widget_preview_scaffold_controller.dart.tmpl index 1a53a1c3d7c..a5b1106c93c 100644 --- a/packages/flutter_tools/templates/widget_preview_scaffold/lib/src/widget_preview_scaffold_controller.dart.tmpl +++ b/packages/flutter_tools/templates/widget_preview_scaffold/lib/src/widget_preview_scaffold_controller.dart.tmpl @@ -3,7 +3,10 @@ // found in the LICENSE file. import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; import 'package:path/path.dart' as path; +import 'package:widget_preview_scaffold/src/dtd/editor_service.dart'; +import 'package:widget_preview_scaffold/src/widget_preview_rendering.dart'; import 'dtd/dtd_services.dart'; import 'widget_preview.dart'; @@ -21,7 +24,11 @@ class WidgetPreviewScaffoldController { required PreviewsCallback previews, @visibleForTesting WidgetPreviewScaffoldDtdServices? dtdServicesOverride, }) : _previews = previews, - dtdServices = dtdServicesOverride ?? WidgetPreviewScaffoldDtdServices(); + dtdServices = dtdServicesOverride ?? WidgetPreviewScaffoldDtdServices() { + // Overrides the default WidgetInspectorService instance to handle selection + // events. + _WidgetPreviewScaffoldInspectorService(dtdServices: dtdServices); + } /// Initializes the controller by establishing a connection to DTD and /// listening for events. @@ -154,3 +161,77 @@ class WidgetPreviewScaffoldController { } } } + +/// A custom [WidgetInspectorService] responsible for routing navigation events +/// to the IDE. +class _WidgetPreviewScaffoldInspectorService with WidgetInspectorService { + _WidgetPreviewScaffoldInspectorService({required this.dtdServices}) { + WidgetInspectorService.instance = this; + } + + final WidgetPreviewScaffoldDtdServices dtdServices; + + // Keys used to specify the creation location of a widget when serializing a + // DiagnosticsNode to JSON. This location is used by the widget inspector + // to jump to the creation location of a selected widget. + static const kFile = 'fileUri'; + static const kLine = 'line'; + static const kColumn = 'column'; + + CodeLocation? _nextNavigationLocation; + + @protected + @override + bool setSelection(Object? object, [String? groupName]) { + // The next navigation event sent to `postEvent` will be for this selection. + // Save the location of preview annotation applications so we can override + // the navigation target in `postEvent`. + if (object is PreviewWidgetElement) { + final previewData = (object.widget as PreviewWidget).preview; + _nextNavigationLocation = CodeLocation( + uri: previewData.scriptUri, + line: previewData.line, + column: previewData.column, + ); + } + final result = super.setSelection(object, groupName); + _nextNavigationLocation = null; + return result; + } + + @override + void postEvent( + String eventKind, + Map eventData, { + String stream = 'Extension', + }) { + // It's unlikely that the widget previewer will be connected to directly by + // an IDE via the VM service, so we forward navigation events via the + // Editor DTD service. + if (eventKind == 'navigate') { + CodeLocation? location = _nextNavigationLocation; + if (eventData case { + kFile: final String file, + kLine: final int line, + kColumn: final int column, + } when location == null) { + location = CodeLocation(uri: file, line: line, column: column); + } else if (location != null) { + // If a [PreviewWidgetElement] was selected, we're not navigating to the + // creation location of the widget. Override the location details in the + // event data, just in case an IDE is attached and listening for + // navigation events through the VM service. + // TODO(bkonyi): determine if this is necessary + eventData.addAll({ + kFile: location.uri, + kLine: location.line!, + kColumn: location.column!, + }); + } + if (location != null) { + dtdServices.navigateToCode(location); + } + } + super.postEvent(eventKind, eventData, stream: stream); + } +} diff --git a/packages/flutter_tools/test/commands.shard/hermetic/widget_preview/preview_code_generator_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/widget_preview/preview_code_generator_test.dart index 9d3d2e71e75..65ec94e110e 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/widget_preview/preview_code_generator_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/widget_preview/preview_code_generator_test.dart @@ -297,18 +297,24 @@ List<_i1.WidgetPreview> previews() => [ _i2.buildWidgetPreview( packageName: 'foo_project', scriptUri: 'STRIPPED', + line: 4, + column: 1, previewFunction: () => _i3.preview(), transformedPreview: const _i4.Preview().transform(), ), _i2.buildWidgetPreview( packageName: 'foo_project', scriptUri: 'STRIPPED', + line: 10, + column: 1, previewFunction: () => _i5.barPreview1(), transformedPreview: const _i4.Preview(group: 'group').transform(), ), _i2.buildWidgetPreview( packageName: 'foo_project', scriptUri: 'STRIPPED', + line: 13, + column: 1, previewFunction: () => _i5.barPreview2(), transformedPreview: const _i4.Preview(brightness: _i6.brightnessConstant).transform(), @@ -316,6 +322,8 @@ List<_i1.WidgetPreview> previews() => [ _i2.buildWidgetPreview( packageName: 'foo_project', scriptUri: 'STRIPPED', + line: 16, + column: 1, previewFunction: () => _i5.barPreview3(), transformedPreview: const _i4.Preview( group: 'group', @@ -334,12 +342,16 @@ List<_i1.WidgetPreview> previews() => [ ..._i2.buildMultiWidgetPreview( packageName: 'foo_project', scriptUri: 'STRIPPED', + line: 51, + column: 1, previewFunction: () => _i11.preview(), preview: const _i11.BrightnessPreview(name: 'Foo'), ), _i2.buildWidgetPreview( packageName: 'foo_project', scriptUri: 'STRIPPED', + line: 52, + column: 1, previewFunction: () => _i11.preview(), transformedPreview: const _i11.FixedSizePreview(name: 'Bar').transform(), @@ -347,6 +359,8 @@ List<_i1.WidgetPreview> previews() => [ _i2.buildWidgetPreviewError( packageName: 'foo_project', scriptUri: 'STRIPPED', + line: 6, + column: 1, packageUri: 'package:foo_project/src/error.dart', functionName: 'preview', dependencyHasErrors: false, @@ -354,6 +368,8 @@ List<_i1.WidgetPreview> previews() => [ _i2.buildWidgetPreviewError( packageName: 'foo_project', scriptUri: 'STRIPPED', + line: 6, + column: 1, packageUri: 'package:foo_project/src/transitive_error.dart', functionName: 'preview', dependencyHasErrors: true, diff --git a/packages/flutter_tools/test/commands.shard/hermetic/widget_preview/utils/preview_details_matcher.dart b/packages/flutter_tools/test/commands.shard/hermetic/widget_preview/utils/preview_details_matcher.dart index 700f597aae9..c82329b7c40 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/widget_preview/utils/preview_details_matcher.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/widget_preview/utils/preview_details_matcher.dart @@ -104,24 +104,24 @@ class PreviewMatcher extends Matcher { ); checkPropertyMatch( name: kWrapper, - actual: item.getFirstField(kWrapper)?.toFunctionValue2()?.displayName, + actual: item.getFirstField(kWrapper)?.toFunctionValue()?.displayName, expected: wrapper, ); checkPropertyMatch( name: kTheme, - actual: item.getFirstField(kTheme)?.toFunctionValue2()?.displayName, + actual: item.getFirstField(kTheme)?.toFunctionValue()?.displayName, expected: theme, ); final DartObject? actualBrightness = item.getFirstField(kBrightness); checkPropertyMatch( name: kBrightness, - actual: (actualBrightness?.isNull ?? true) ? null : actualBrightness!.variable2!.toString(), + actual: (actualBrightness?.isNull ?? true) ? null : actualBrightness!.variable!.toString(), expected: brightness, ); checkPropertyMatch( name: kLocalizations, - actual: item.getFirstField(kLocalizations)?.toFunctionValue2()?.displayName, + actual: item.getFirstField(kLocalizations)?.toFunctionValue()?.displayName, expected: localizations, ); return matches; diff --git a/packages/flutter_tools/test/commands.shard/permeable/widget_preview/widget_preview_test.dart b/packages/flutter_tools/test/commands.shard/permeable/widget_preview/widget_preview_test.dart index c8a6f4276cb..30112f186ea 100644 --- a/packages/flutter_tools/test/commands.shard/permeable/widget_preview/widget_preview_test.dart +++ b/packages/flutter_tools/test/commands.shard/permeable/widget_preview/widget_preview_test.dart @@ -335,6 +335,8 @@ List<_i1.WidgetPreview> previews() => [ _i2.buildWidgetPreview( packageName: 'flutter_project', scriptUri: 'STRIPPED', + line: 4, + column: 1, previewFunction: () => _i3.preview(), transformedPreview: const _i4.Preview(name: 'preview').transform(), ) 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 b0cd70e13e9..2c68f084fb4 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 @@ -593,6 +593,7 @@ Review licenses that have not been accepted (y/N)? ); }); + // Warning test not available when minimum and error are aligned. testUsingContext('detects minimum required java version', () async { // Test with older version of JDK final Platform platform = FakePlatform() @@ -636,49 +637,6 @@ Review licenses that have not been accepted (y/N)? ); }); - testUsingContext('detects minimum recommended java version', () async { - // Test with older version of JDK - final Platform platform = FakePlatform() - ..environment = { - 'HOME': '/home/me', - Java.javaHomeEnvironmentVariable: 'home/java', - 'PATH': '', - }; - final sdkVersion = FakeAndroidSdkVersion() - ..sdkLevel = gradle_utils.compileSdkVersionInt - ..buildToolsVersion = gradle_utils.minBuildToolsVersion; - - // Mock a pass through scenario to reach _checkJavaVersion() - sdk - ..licensesAvailable = true - ..platformToolsAvailable = true - ..cmdlineToolsAvailable = true - ..directory = fileSystem.directory('/foo/bar') - ..sdkManagerPath = '/foo/bar/sdkmanager' - ..emulatorPath = 'path/to/emulator'; - sdk.latestVersion = sdkVersion; - - const javaVersionText = 'openjdk version "16.0.1"'; - final String errorMessage = UserMessages().androidJavaMinimumVersion(javaVersionText); - - final ValidationResult validationResult = await AndroidValidator( - java: FakeJava(version: const Version.withText(16, 0, 1, javaVersionText)), - androidSdk: sdk, - logger: logger, - platform: platform, - userMessages: UserMessages(), - processManager: processManager, - ).validate(); - expect(validationResult.type, ValidationType.success); - expect(validationResult.messages.last.message, errorMessage); - expect( - validationResult.messages.any( - (ValidationMessage message) => message.message.contains('Unable to locate Android SDK'), - ), - false, - ); - }); - testWithoutContext('Mentions `flutter config --android-sdk if user has no AndroidSdk`', () async { final ValidationResult validationResult = await AndroidValidator( java: FakeJava(), diff --git a/packages/flutter_tools/test/general.shard/features_test.dart b/packages/flutter_tools/test/general.shard/features_test.dart index ed8eeae18b4..86dcfa7d541 100644 --- a/packages/flutter_tools/test/general.shard/features_test.dart +++ b/packages/flutter_tools/test/general.shard/features_test.dart @@ -334,7 +334,7 @@ void main() { nativeAssets, allOf([ _onChannelIs('master', available: true, enabledByDefault: true), - _onChannelIs('stable', available: false, enabledByDefault: false), + _onChannelIs('stable', available: true, enabledByDefault: true), _onChannelIs('beta', available: true, enabledByDefault: true), ]), ); diff --git a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/lib/src/utils.dart b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/lib/src/utils.dart index f66c203e5b2..05d0bef7315 100644 --- a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/lib/src/utils.dart +++ b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/lib/src/utils.dart @@ -9,6 +9,8 @@ import 'package:widget_preview_scaffold/src/widget_preview.dart'; Iterable buildMultiWidgetPreview({ required String packageName, required String scriptUri, + required int line, + required int column, required MultiPreview preview, required Object? Function() previewFunction, }) { @@ -16,6 +18,8 @@ Iterable buildMultiWidgetPreview({ (p) => buildWidgetPreview( packageName: packageName, scriptUri: scriptUri, + line: line, + column: column, transformedPreview: p, previewFunction: previewFunction, ), @@ -25,6 +29,8 @@ Iterable buildMultiWidgetPreview({ WidgetPreview buildWidgetPreview({ required String packageName, required String scriptUri, + required int line, + required int column, required Preview transformedPreview, required Object? Function() previewFunction, }) { @@ -39,6 +45,8 @@ WidgetPreview buildWidgetPreview({ return WidgetPreview( builder: previewBuilder, scriptUri: scriptUri, + line: line, + column: column, previewData: transformedPreview, packageName: packageName, ); @@ -47,6 +55,8 @@ WidgetPreview buildWidgetPreview({ WidgetPreview buildWidgetPreviewError({ required String packageName, required String scriptUri, + required int line, + required int column, required String packageUri, required String functionName, required bool dependencyHasErrors, @@ -58,6 +68,8 @@ WidgetPreview buildWidgetPreviewError({ return WidgetPreview( builder: () => Text('$functionName: $errorMessage'), scriptUri: scriptUri, + line: line, + column: column, previewData: const Preview(group: 'Invalid Previews'), packageName: packageName, ); diff --git a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/lib/src/widget_preview.dart b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/lib/src/widget_preview.dart index 2c4af1eddf5..29be79b4769 100644 --- a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/lib/src/widget_preview.dart +++ b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/lib/src/widget_preview.dart @@ -31,15 +31,33 @@ class WidgetPreview { const WidgetPreview({ required this.builder, required this.scriptUri, + required this.line, + required this.column, required this.previewData, required this.packageName, }); + @visibleForTesting + const WidgetPreview.test({ + required this.builder, + required this.previewData, + this.scriptUri = '', + this.line = -1, + this.column = -1, + this.packageName = '', + }); + /// The absolute file:// URI pointing to the script containing this preview. /// /// This matches the URI format sent by IDEs for active location change events. final String scriptUri; + /// The line at which the Preview annotation was applied. + final int line; + + /// The column at which the Preview annotation was applied. + final int column; + /// The name of the package in which a preview was defined. /// /// For example, if a preview is defined in 'package:foo/src/bar.dart', this @@ -104,6 +122,7 @@ class WidgetPreview { void debugFillProperties(DiagnosticPropertiesBuilder properties) { properties ..add(DiagnosticsProperty('name', name, ifNull: 'not set')) + ..add(DiagnosticsProperty('group', previewData.group)) ..add(DiagnosticsProperty('size', size)) ..add(DiagnosticsProperty('textScaleFactor', textScaleFactor)) ..add(DiagnosticsProperty('theme', theme)) diff --git a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/lib/src/widget_preview_rendering.dart b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/lib/src/widget_preview_rendering.dart index 2549899543a..47faa6c5c10 100644 --- a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/lib/src/widget_preview_rendering.dart +++ b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/lib/src/widget_preview_rendering.dart @@ -178,12 +178,16 @@ class NoPreviewsDetectedWidget extends StatelessWidget { } } +/// A wrapper that serves as the root entry for a single preview in the widget inspector. class PreviewWidget extends StatelessWidget { const PreviewWidget({super.key, required this.preview, required this.child}); final WidgetPreview preview; final Widget child; + @override + StatelessElement createElement() => PreviewWidgetElement(this); + @override Widget build(BuildContext context) { return child; @@ -191,7 +195,9 @@ class PreviewWidget extends StatelessWidget { @override String toStringShort() { - final StringBuffer buffer = StringBuffer('@Preview'); + final StringBuffer buffer = StringBuffer( + '@${preview.previewData.runtimeType}', + ); if (preview.name != null) { buffer.write('(name: "${preview.name}")'); } @@ -205,6 +211,12 @@ class PreviewWidget extends StatelessWidget { } } +/// A custom [StatelessElement] with the sole purpose of simplifying identifying +/// selections of @Preview annotations in the widget inspector. +class PreviewWidgetElement extends StatelessElement { + PreviewWidgetElement(super.widget); +} + class WidgetPreviewGroupWidget extends StatelessWidget { const WidgetPreviewGroupWidget({ super.key, diff --git a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/lib/src/widget_preview_scaffold_controller.dart b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/lib/src/widget_preview_scaffold_controller.dart index 1a53a1c3d7c..a5b1106c93c 100644 --- a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/lib/src/widget_preview_scaffold_controller.dart +++ b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/lib/src/widget_preview_scaffold_controller.dart @@ -3,7 +3,10 @@ // found in the LICENSE file. import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; import 'package:path/path.dart' as path; +import 'package:widget_preview_scaffold/src/dtd/editor_service.dart'; +import 'package:widget_preview_scaffold/src/widget_preview_rendering.dart'; import 'dtd/dtd_services.dart'; import 'widget_preview.dart'; @@ -21,7 +24,11 @@ class WidgetPreviewScaffoldController { required PreviewsCallback previews, @visibleForTesting WidgetPreviewScaffoldDtdServices? dtdServicesOverride, }) : _previews = previews, - dtdServices = dtdServicesOverride ?? WidgetPreviewScaffoldDtdServices(); + dtdServices = dtdServicesOverride ?? WidgetPreviewScaffoldDtdServices() { + // Overrides the default WidgetInspectorService instance to handle selection + // events. + _WidgetPreviewScaffoldInspectorService(dtdServices: dtdServices); + } /// Initializes the controller by establishing a connection to DTD and /// listening for events. @@ -154,3 +161,77 @@ class WidgetPreviewScaffoldController { } } } + +/// A custom [WidgetInspectorService] responsible for routing navigation events +/// to the IDE. +class _WidgetPreviewScaffoldInspectorService with WidgetInspectorService { + _WidgetPreviewScaffoldInspectorService({required this.dtdServices}) { + WidgetInspectorService.instance = this; + } + + final WidgetPreviewScaffoldDtdServices dtdServices; + + // Keys used to specify the creation location of a widget when serializing a + // DiagnosticsNode to JSON. This location is used by the widget inspector + // to jump to the creation location of a selected widget. + static const kFile = 'fileUri'; + static const kLine = 'line'; + static const kColumn = 'column'; + + CodeLocation? _nextNavigationLocation; + + @protected + @override + bool setSelection(Object? object, [String? groupName]) { + // The next navigation event sent to `postEvent` will be for this selection. + // Save the location of preview annotation applications so we can override + // the navigation target in `postEvent`. + if (object is PreviewWidgetElement) { + final previewData = (object.widget as PreviewWidget).preview; + _nextNavigationLocation = CodeLocation( + uri: previewData.scriptUri, + line: previewData.line, + column: previewData.column, + ); + } + final result = super.setSelection(object, groupName); + _nextNavigationLocation = null; + return result; + } + + @override + void postEvent( + String eventKind, + Map eventData, { + String stream = 'Extension', + }) { + // It's unlikely that the widget previewer will be connected to directly by + // an IDE via the VM service, so we forward navigation events via the + // Editor DTD service. + if (eventKind == 'navigate') { + CodeLocation? location = _nextNavigationLocation; + if (eventData case { + kFile: final String file, + kLine: final int line, + kColumn: final int column, + } when location == null) { + location = CodeLocation(uri: file, line: line, column: column); + } else if (location != null) { + // If a [PreviewWidgetElement] was selected, we're not navigating to the + // creation location of the widget. Override the location details in the + // event data, just in case an IDE is attached and listening for + // navigation events through the VM service. + // TODO(bkonyi): determine if this is necessary + eventData.addAll({ + kFile: location.uri, + kLine: location.line!, + kColumn: location.column!, + }); + } + if (location != null) { + dtdServices.navigateToCode(location); + } + } + super.postEvent(eventKind, eventData, stream: stream); + } +} diff --git a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/custom_previews_test.dart b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/custom_previews_test.dart index 5402ba76904..76b0f83befb 100644 --- a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/custom_previews_test.dart +++ b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/custom_previews_test.dart @@ -71,6 +71,8 @@ WidgetPreviewerWidgetScaffolding previewsForCustomMultiPreview() { scriptUri: '', preview: BrightnessPreview(name: 'MyPreview'), previewFunction: () => Text('Foo'), + line: -1, + column: -1, ); final controller = FakeWidgetPreviewScaffoldController(); return WidgetPreviewerWidgetScaffolding( diff --git a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/error_widget_test.dart b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/error_widget_test.dart index f160845a5d2..73f85d39e6d 100644 --- a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/error_widget_test.dart +++ b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/error_widget_test.dart @@ -42,11 +42,9 @@ void main() { final controller = WidgetPreviewScaffoldController( dtdServicesOverride: fakeDtdServices, previews: () => [ - WidgetPreview( + WidgetPreview.test( builder: () => throw Exception('Error!'), - scriptUri: '', previewData: Preview(), - packageName: '', ), ], ); diff --git a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/filter_by_selected_file_test.dart b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/filter_by_selected_file_test.dart index 75ac17ec8f5..369dbbddd98 100644 --- a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/filter_by_selected_file_test.dart +++ b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/filter_by_selected_file_test.dart @@ -29,17 +29,15 @@ Future testImpl({ isWindows: isWindows, ); final previews = [ - WidgetPreview( + WidgetPreview.test( builder: () => Text('widget1'), scriptUri: script1Uri.toString(), previewData: Preview(group: 'group'), - packageName: '', ), - WidgetPreview( + WidgetPreview.test( builder: () => Text('widget2'), scriptUri: script2Uri.toString(), previewData: Preview(group: 'group'), - packageName: '', ), ]; final controller = FakeWidgetPreviewScaffoldController( @@ -189,17 +187,13 @@ void main() { ) async { final dtdServices = FakeWidgetPreviewScaffoldDtdServices(); final previews = [ - WidgetPreview( + WidgetPreview.test( builder: () => Text('widget1'), - scriptUri: '', previewData: Preview(group: 'group'), - packageName: '', ), - WidgetPreview( + WidgetPreview.test( builder: () => Text('widget2'), - scriptUri: '', previewData: Preview(group: 'group'), - packageName: '', ), ]; final controller = FakeWidgetPreviewScaffoldController( diff --git a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/localizations_test.dart b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/localizations_test.dart index 0d6f1c5c036..f0e93d4b271 100644 --- a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/localizations_test.dart +++ b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/localizations_test.dart @@ -37,11 +37,9 @@ WidgetPreviewerWidgetScaffolding previewForLocalizations({ return WidgetPreviewerWidgetScaffolding( child: WidgetPreviewWidget( controller: controller, - preview: WidgetPreview( - scriptUri: '', + preview: WidgetPreview.test( builder: () => Text('Foo', key: key), previewData: Preview(localizations: previewLocalizationsData), - packageName: '', ), ), ); diff --git a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/no_previews_detected_test.dart b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/no_previews_detected_test.dart index 91ddbe2b9b0..4ebd6318800 100644 --- a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/no_previews_detected_test.dart +++ b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/no_previews_detected_test.dart @@ -50,6 +50,8 @@ void main() { currentPreviews.add( WidgetPreview( scriptUri: '', + line: -1, + column: -1, builder: () => const Text('Foo'), previewData: Preview(), packageName: '', diff --git a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/soft_restart_test.dart b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/soft_restart_test.dart index 8326a7b479a..5c6249e1fed 100644 --- a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/soft_restart_test.dart +++ b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/soft_restart_test.dart @@ -23,11 +23,9 @@ void main() { final widgetPreview = WidgetPreviewerWidgetScaffolding( child: WidgetPreviewWidget( controller: controller, - preview: WidgetPreview( - scriptUri: '', + preview: WidgetPreview.test( builder: () => const Text(kTestText), previewData: Preview(), - packageName: '', ), ), ); diff --git a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/theming_test.dart b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/theming_test.dart index 0c2bb23ead8..2735b1395cb 100644 --- a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/theming_test.dart +++ b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/theming_test.dart @@ -55,11 +55,9 @@ WidgetPreviewerWidgetScaffolding previewForBrightness({ platformBrightness: platformBrightness ?? Brightness.light, child: WidgetPreviewWidget( controller: controller, - preview: WidgetPreview( - scriptUri: '', + preview: WidgetPreview.test( builder: () => Text('Foo', key: key), previewData: Preview(theme: previewTheme, brightness: brightness), - packageName: '', ), ), ); diff --git a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/widget_inspector_test.dart b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/widget_inspector_test.dart index 59f975cf102..fdd17cb97fc 100644 --- a/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/widget_inspector_test.dart +++ b/packages/flutter_tools/test/widget_preview_scaffold.shard/widget_preview_scaffold/test/widget_inspector_test.dart @@ -24,11 +24,9 @@ void main() { for (int i = 0; i < kNumPreviewedWidgets; ++i) WidgetPreviewWidget( controller: controller, - preview: WidgetPreview( - scriptUri: '', + preview: WidgetPreview.test( builder: () => Text('$kTestText$i'), previewData: Preview(), - packageName: '', ), ), ], @@ -87,4 +85,57 @@ void main() { await tester.pump(); expect(widgetInspectorFinder, findsNothing); }); + + testWidgets('WidgetInspector navigates to Preview application location', ( + tester, + ) async { + final controller = FakeWidgetPreviewScaffoldController(); + await controller.initialize(); + final dtd = controller.dtdServices as FakeWidgetPreviewScaffoldDtdServices; + + final service = WidgetInspectorService.instance; + service.isSelectMode = true; + + const kLine = 123; + const kColumn = 456; + const kScriptUri = 'file:///script/containing/preview.dart'; + + final widgetPreview = WidgetPreviewerWidgetScaffolding( + child: Column( + children: [ + WidgetPreviewWidget( + controller: controller, + preview: WidgetPreview.test( + builder: () => Text(''), + previewData: Preview(), + line: kLine, + column: kColumn, + scriptUri: kScriptUri, + ), + ), + ], + ), + ); + + await tester.pumpWidget(widgetPreview); + final element = find.byType(PreviewWidget).evaluate().first; + + // Select the WidgetPreviewWidget, which acts as the root entry of the + // preview within the inspector. + expect(service.selection.current, isNull); + // ignore: invalid_use_of_protected_member + service.setSelection(element); + + // Ensure that a navigation event has been sent to the IDE via DTD as a + // result of the inspector selection. + expect(dtd.navigationEvents, hasLength(1)); + + // The navigation event should be to the location of the preview provided + // to the WidgetPreviewWidget, not the actual creation location of the + // WidgetPreviewWidget.annotation location + final codeLocation = dtd.navigationEvents.single; + expect(codeLocation.uri, kScriptUri); + expect(codeLocation.line, kLine); + expect(codeLocation.column, kColumn); + }); } diff --git a/pubspec.lock b/pubspec.lock index 6f9c0922ed2..a31d0bd525e 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -126,10 +126,10 @@ packages: dependency: "direct main" description: name: code_assets - sha256: "3b182b03a2f263ad6ab47cdadf9b64daa1d2d72ac941a277f685fb77ba96cbd5" + sha256: "5865a34983367f6884e8311f67d9ae459945b99bad20c0e66484a1aae7feaae0" url: "https://pub.dev" source: hosted - version: "0.19.6" + version: "0.19.7" collection: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index 2c63dafa0ca..c4b523044cf 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -90,7 +90,7 @@ dependencies: checked_yaml: 2.0.4 cli_config: 0.2.0 clock: 1.1.2 - code_assets: 0.19.6 + code_assets: 0.19.7 collection: 1.19.1 convert: 3.1.2 coverage: 1.15.0 @@ -212,4 +212,4 @@ dependencies: pedantic: 1.11.1 quiver: 3.2.2 yaml_edit: 2.2.2 -# PUBSPEC CHECKSUM: 5pih92 +# PUBSPEC CHECKSUM: 9hqic