diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index 7f37acc4cc..120597e6f1 100755 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -411,6 +411,9 @@ FILE: ../../../flutter/lib/ui/semantics/semantics_update.cc FILE: ../../../flutter/lib/ui/semantics/semantics_update.h FILE: ../../../flutter/lib/ui/semantics/semantics_update_builder.cc FILE: ../../../flutter/lib/ui/semantics/semantics_update_builder.h +FILE: ../../../flutter/lib/ui/semantics/semantics_update_builder_unittests.cc +FILE: ../../../flutter/lib/ui/semantics/string_attribute.cc +FILE: ../../../flutter/lib/ui/semantics/string_attribute.h FILE: ../../../flutter/lib/ui/snapshot_delegate.h FILE: ../../../flutter/lib/ui/text.dart FILE: ../../../flutter/lib/ui/text/asset_manager_font_provider.cc diff --git a/engine/src/flutter/fml/platform/android/jni_util.cc b/engine/src/flutter/fml/platform/android/jni_util.cc index c454558404..fd54a55c4b 100644 --- a/engine/src/flutter/fml/platform/android/jni_util.cc +++ b/engine/src/flutter/fml/platform/android/jni_util.cc @@ -132,14 +132,33 @@ ScopedJavaLocalRef VectorToStringArray( ScopedJavaLocalRef string_clazz(env, env->FindClass("java/lang/String")); FML_DCHECK(!string_clazz.is_null()); - jobjectArray joa = + jobjectArray java_array = env->NewObjectArray(vector.size(), string_clazz.obj(), NULL); ASSERT_NO_EXCEPTION(); for (size_t i = 0; i < vector.size(); ++i) { ScopedJavaLocalRef item = StringToJavaString(env, vector[i]); - env->SetObjectArrayElement(joa, i, item.obj()); + env->SetObjectArrayElement(java_array, i, item.obj()); } - return ScopedJavaLocalRef(env, joa); + return ScopedJavaLocalRef(env, java_array); +} + +ScopedJavaLocalRef VectorToBufferArray( + JNIEnv* env, + const std::vector>& vector) { + FML_DCHECK(env); + ScopedJavaLocalRef byte_buffer_clazz( + env, env->FindClass("java/nio/ByteBuffer")); + FML_DCHECK(!byte_buffer_clazz.is_null()); + jobjectArray java_array = + env->NewObjectArray(vector.size(), byte_buffer_clazz.obj(), NULL); + ASSERT_NO_EXCEPTION(); + for (size_t i = 0; i < vector.size(); ++i) { + ScopedJavaLocalRef item( + env, + env->NewDirectByteBuffer((void*)(vector[i].data()), vector[i].size())); + env->SetObjectArrayElement(java_array, i, item.obj()); + } + return ScopedJavaLocalRef(env, java_array); } bool HasException(JNIEnv* env) { diff --git a/engine/src/flutter/fml/platform/android/jni_util.h b/engine/src/flutter/fml/platform/android/jni_util.h index c0e3fd31f3..4f4d778bf7 100644 --- a/engine/src/flutter/fml/platform/android/jni_util.h +++ b/engine/src/flutter/fml/platform/android/jni_util.h @@ -34,6 +34,10 @@ ScopedJavaLocalRef VectorToStringArray( JNIEnv* env, const std::vector& vector); +ScopedJavaLocalRef VectorToBufferArray( + JNIEnv* env, + const std::vector>& vector); + bool HasException(JNIEnv* env); bool ClearException(JNIEnv* env); diff --git a/engine/src/flutter/lib/ui/BUILD.gn b/engine/src/flutter/lib/ui/BUILD.gn index fa74debca3..5522524b28 100644 --- a/engine/src/flutter/lib/ui/BUILD.gn +++ b/engine/src/flutter/lib/ui/BUILD.gn @@ -82,6 +82,8 @@ source_set("ui") { "semantics/semantics_update.h", "semantics/semantics_update_builder.cc", "semantics/semantics_update_builder.h", + "semantics/string_attribute.cc", + "semantics/string_attribute.h", "snapshot_delegate.h", "text/asset_manager_font_provider.cc", "text/asset_manager_font_provider.h", @@ -205,6 +207,7 @@ if (enable_unittests) { "painting/path_unittests.cc", "painting/single_frame_codec_unittests.cc", "painting/vertices_unittests.cc", + "semantics/semantics_update_builder_unittests.cc", "window/platform_configuration_unittests.cc", "window/pointer_data_packet_converter_unittests.cc", ] diff --git a/engine/src/flutter/lib/ui/dart_ui.cc b/engine/src/flutter/lib/ui/dart_ui.cc index c22b26b17d..7fca5720b6 100644 --- a/engine/src/flutter/lib/ui/dart_ui.cc +++ b/engine/src/flutter/lib/ui/dart_ui.cc @@ -26,6 +26,7 @@ #include "flutter/lib/ui/painting/vertices.h" #include "flutter/lib/ui/semantics/semantics_update.h" #include "flutter/lib/ui/semantics/semantics_update_builder.h" +#include "flutter/lib/ui/semantics/string_attribute.h" #include "flutter/lib/ui/text/font_collection.h" #include "flutter/lib/ui/text/paragraph.h" #include "flutter/lib/ui/text/paragraph_builder.h" @@ -74,6 +75,7 @@ void DartUI::InitForGlobal() { ImageShader::RegisterNatives(g_natives); ImmutableBuffer::RegisterNatives(g_natives); IsolateNameServerNatives::RegisterNatives(g_natives); + NativeStringAttribute::RegisterNatives(g_natives); Paragraph::RegisterNatives(g_natives); ParagraphBuilder::RegisterNatives(g_natives); Picture::RegisterNatives(g_natives); diff --git a/engine/src/flutter/lib/ui/fixtures/ui_test.dart b/engine/src/flutter/lib/ui/fixtures/ui_test.dart index 4cba1936b6..3f33b91cd6 100644 --- a/engine/src/flutter/lib/ui/fixtures/ui_test.dart +++ b/engine/src/flutter/lib/ui/fixtures/ui_test.dart @@ -58,6 +58,97 @@ void createVertices() { } void _validateVertices(Vertices vertices) native 'ValidateVertices'; +@pragma('vm:entry-point') +void sendSemanticsUpdate() { + final SemanticsUpdateBuilder builder = SemanticsUpdateBuilder(); + final String label = "label"; + final List labelAttributes = [ + SpellOutStringAttribute(range: TextRange(start: 1, end: 2)), + ]; + + final String value = "value"; + final List valueAttributes = [ + SpellOutStringAttribute(range: TextRange(start: 2, end: 3)), + ]; + + final String increasedValue = "increasedValue"; + final List increasedValueAttributes = [ + SpellOutStringAttribute(range: TextRange(start: 4, end: 5)), + ]; + + final String decreasedValue = "decreasedValue"; + final List decreasedValueAttributes = [ + SpellOutStringAttribute(range: TextRange(start: 5, end: 6)), + ]; + + final String hint = "hint"; + final List hintAttributes = [ + LocaleStringAttribute( + locale: Locale('en', 'MX'), range: TextRange(start: 0, end: 1), + ), + ]; + + final Float64List transform = Float64List(16); + final Int32List childrenInTraversalOrder = Int32List(0); + final Int32List childrenInHitTestOrder = Int32List(0); + final Int32List additionalActions = Int32List(0); + transform[0] = 1; + transform[1] = 0; + transform[2] = 0; + transform[3] = 0; + + transform[4] = 0; + transform[5] = 1; + transform[6] = 0; + transform[7] = 0; + + transform[8] = 0; + transform[9] = 0; + transform[10] = 1; + transform[11] = 0; + + transform[12] = 0; + transform[13] = 0; + transform[14] = 0; + transform[15] = 0; + builder.updateNode( + id: 0, + flags: 0, + actions: 0, + maxValueLength: 0, + currentValueLength: 0, + textSelectionBase: -1, + textSelectionExtent: -1, + platformViewId: -1, + scrollChildren: 0, + scrollIndex: 0, + scrollPosition: 0, + scrollExtentMax: 0, + scrollExtentMin: 0, + rect: Rect.fromLTRB(0, 0, 10, 10), + elevation: 0, + thickness: 0, + label: label, + labelAttributes: labelAttributes, + value: value, + valueAttributes: valueAttributes, + increasedValue: increasedValue, + increasedValueAttributes: increasedValueAttributes, + decreasedValue: decreasedValue, + decreasedValueAttributes: decreasedValueAttributes, + hint: hint, + hintAttributes: hintAttributes, + textDirection: TextDirection.ltr, + transform: transform, + childrenInTraversalOrder: childrenInTraversalOrder, + childrenInHitTestOrder: childrenInHitTestOrder, + additionalActions: additionalActions + ); + _semanticsUpdate(builder.build()); +} + +void _semanticsUpdate(SemanticsUpdate update) native 'SemanticsUpdate'; + @pragma('vm:entry-point') void createPath() { final Path path = Path()..lineTo(10, 10); diff --git a/engine/src/flutter/lib/ui/semantics.dart b/engine/src/flutter/lib/ui/semantics.dart index 1e5baa4158..88e755514d 100644 --- a/engine/src/flutter/lib/ui/semantics.dart +++ b/engine/src/flutter/lib/ui/semantics.dart @@ -641,6 +641,108 @@ class SemanticsFlag { } } +// When adding a new StringAttribute, the classes in these files must be +// updated as well. +// * engine/src/flutter/lib/web_ui/lib/src/ui/semantics.dart +// * engine/src/flutter/lib/ui/semantics/string_attribute.h +// * engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java + +/// An abstract interface for string attributes that affects how assistive +/// technologies, e.g. VoiceOver or TalkBack, treat the text. +/// +/// See also: +/// +/// * [AttributedString], where the string attributes are used. +/// * [SpellOutStringAttribute], which causes the assistive technologies to +/// spell out the string character by character when announcing the string. +/// * [LocaleStringAttribute], which causes the assistive technologies to +/// treat the string in the specific language. +abstract class StringAttribute extends NativeFieldWrapperClass2 { + StringAttribute._({ + required this.range, + }); + + // The range of the text to which this attribute applies. + final TextRange range; + + // Returns a copy of this atttribute with the given range. + StringAttribute copy({required TextRange range}); +} + +/// A string attribute that causes the assistive technologies, e.g. VoiceOver, +/// to spell out the string character by character. +/// +/// See also: +/// +/// * [AttributedString], where the string attributes are used. +/// * [LocaleStringAttribute], which causes the assistive technologies to +/// treat the string in the specific language. +class SpellOutStringAttribute extends StringAttribute { + /// Creates a string attribute that denotes the text in [range] must be + /// spell out when the assistive technologies announce the string. + SpellOutStringAttribute({ + required TextRange range, + }) : super._(range: range) { + _initSpellOutStringAttribute(this, range.start, range.end); + } + + void _initSpellOutStringAttribute( + SpellOutStringAttribute instance, + int start, + int end, + ) native 'NativeStringAttribute_initSpellOutStringAttribute'; + + @override + StringAttribute copy({required TextRange range}) { + return SpellOutStringAttribute(range: range); + } + + @override + String toString() { + return 'SpellOutStringAttribute($range)'; + } +} + +/// A string attribute that causes the assistive technologies, e.g. VoiceOver, +/// to treat string as a certain language. +/// +/// See also: +/// +/// * [AttributedString], where the string attributes are used. +/// * [SpellOutStringAttribute], which causes the assistive technologies to +/// spell out the string character by character when announcing the string. +class LocaleStringAttribute extends StringAttribute { + /// Creates a string attribute that denotes the text in [range] must be + /// treated as the language specified by the [locale] when the assistive + /// technologies announce the string. + LocaleStringAttribute({ + required TextRange range, + required this.locale, + }) : super._(range: range) { + _initLocaleStringAttribute(this, range.start, range.end, locale.toLanguageTag()); + } + + /// The lanuage of this attribute. + final Locale locale; + + void _initLocaleStringAttribute( + LocaleStringAttribute instance, + int start, + int end, + String locale, + ) native 'NativeStringAttribute_initLocaleStringAttribute'; + + @override + StringAttribute copy({required TextRange range}) { + return LocaleStringAttribute(range: range, locale: locale); + } + + @override + String toString() { + return 'LocaleStringAttribute($range, ${locale.toLanguageTag()})'; + } +} + /// An object that creates [SemanticsUpdate] objects. /// /// Once created, the [SemanticsUpdate] objects can be passed to @@ -686,6 +788,12 @@ class SemanticsUpdateBuilder extends NativeFieldWrapperClass2 { /// string describes what result an action performed on this node has. The /// reading direction of all these strings is given by `textDirection`. /// + /// The `labelAttirbutes`, `valueAttirbutes`, `hintAttributes`, + /// `increasedValueAttirbutes`, and `decreasedValueAttributes` are the lists of + /// [StringAttribute] carried by the `label`, `value`, `hint`, `increasedValue`, + /// and `decreasedValue` respectively. Their contents must not be changed during + /// the semantics update. + /// /// The fields `textSelectionBase` and `textSelectionExtent` describe the /// currently selected text within `value`. A value of -1 indicates no /// current text selection base or extent. @@ -743,10 +851,15 @@ class SemanticsUpdateBuilder extends NativeFieldWrapperClass2 { required double thickness, required Rect rect, required String label, - required String hint, + List? labelAttributes, required String value, + List? valueAttributes, required String increasedValue, + List? increasedValueAttributes, required String decreasedValue, + List? decreasedValueAttributes, + required String hint, + List? hintAttributes, TextDirection? textDirection, required Float64List transform, required Int32List childrenInTraversalOrder, @@ -779,10 +892,15 @@ class SemanticsUpdateBuilder extends NativeFieldWrapperClass2 { elevation, thickness, label, - hint, + labelAttributes, value, + valueAttributes, increasedValue, + increasedValueAttributes, decreasedValue, + decreasedValueAttributes, + hint, + hintAttributes, textDirection != null ? textDirection.index + 1 : 0, transform, childrenInTraversalOrder, @@ -811,10 +929,15 @@ class SemanticsUpdateBuilder extends NativeFieldWrapperClass2 { double elevation, double thickness, String label, - String hint, + List? labelAttributes, String value, + List? valueAttributes, String increasedValue, + List? increasedValueAttributes, String decreasedValue, + List? decreasedValueAttributes, + String hint, + List? hintAttributes, int textDirection, Float64List transform, Int32List childrenInTraversalOrder, diff --git a/engine/src/flutter/lib/ui/semantics/semantics_node.h b/engine/src/flutter/lib/ui/semantics/semantics_node.h index ea2183b23c..1d798d66e3 100644 --- a/engine/src/flutter/lib/ui/semantics/semantics_node.h +++ b/engine/src/flutter/lib/ui/semantics/semantics_node.h @@ -13,6 +13,8 @@ #include "third_party/skia/include/core/SkM44.h" #include "third_party/skia/include/core/SkRect.h" +#include "flutter/lib/ui/semantics/string_attribute.h" + namespace flutter { // Must match the SemanticsAction enum in semantics.dart and in each of the @@ -115,10 +117,15 @@ struct SemanticsNode { double elevation = 0.0; double thickness = 0.0; std::string label; + StringAttributes labelAttributes; std::string hint; + StringAttributes hintAttributes; std::string value; + StringAttributes valueAttributes; std::string increasedValue; + StringAttributes increasedValueAttributes; std::string decreasedValue; + StringAttributes decreasedValueAttributes; int32_t textDirection = 0; // 0=unknown, 1=rtl, 2=ltr SkRect rect = SkRect::MakeEmpty(); // Local space, relative to parent. diff --git a/engine/src/flutter/lib/ui/semantics/semantics_update_builder.cc b/engine/src/flutter/lib/ui/semantics/semantics_update_builder.cc index 3b92bc0c9d..beae3a3b1e 100644 --- a/engine/src/flutter/lib/ui/semantics/semantics_update_builder.cc +++ b/engine/src/flutter/lib/ui/semantics/semantics_update_builder.cc @@ -13,6 +13,14 @@ namespace flutter { +void pushStringAttributes( + StringAttributes& destination, + const std::vector& native_attributes) { + for (const auto& native_attribute : native_attributes) { + destination.push_back(native_attribute->GetAttribute()); + } +} + static void SemanticsUpdateBuilder_constructor(Dart_NativeArguments args) { UIDartState::ThrowIfUIOperationsProhibited(); DartCallConstructor(&SemanticsUpdateBuilder::create, args); @@ -59,10 +67,15 @@ void SemanticsUpdateBuilder::updateNode( double elevation, double thickness, std::string label, - std::string hint, + std::vector labelAttributes, std::string value, + std::vector valueAttributes, std::string increasedValue, + std::vector increasedValueAttributes, std::string decreasedValue, + std::vector decreasedValueAttributes, + std::string hint, + std::vector hintAttributes, int textDirection, const tonic::Float64List& transform, const tonic::Int32List& childrenInTraversalOrder, @@ -92,10 +105,15 @@ void SemanticsUpdateBuilder::updateNode( node.elevation = elevation; node.thickness = thickness; node.label = label; - node.hint = hint; + pushStringAttributes(node.labelAttributes, labelAttributes); node.value = value; + pushStringAttributes(node.valueAttributes, valueAttributes); node.increasedValue = increasedValue; + pushStringAttributes(node.increasedValueAttributes, increasedValueAttributes); node.decreasedValue = decreasedValue; + pushStringAttributes(node.decreasedValueAttributes, decreasedValueAttributes); + node.hint = hint; + pushStringAttributes(node.hintAttributes, hintAttributes); node.textDirection = textDirection; SkScalar scalarTransform[16]; for (int i = 0; i < 16; ++i) { diff --git a/engine/src/flutter/lib/ui/semantics/semantics_update_builder.h b/engine/src/flutter/lib/ui/semantics/semantics_update_builder.h index a183e1384b..96c29a1bce 100644 --- a/engine/src/flutter/lib/ui/semantics/semantics_update_builder.h +++ b/engine/src/flutter/lib/ui/semantics/semantics_update_builder.h @@ -5,6 +5,9 @@ #ifndef FLUTTER_LIB_UI_SEMANTICS_SEMANTICS_UPDATE_BUILDER_H_ #define FLUTTER_LIB_UI_SEMANTICS_SEMANTICS_UPDATE_BUILDER_H_ +#include +#include + #include "flutter/lib/ui/dart_wrapper.h" #include "flutter/lib/ui/semantics/semantics_update.h" #include "third_party/tonic/typed_data/typed_list.h" @@ -43,10 +46,15 @@ class SemanticsUpdateBuilder double elevation, double thickness, std::string label, - std::string hint, + std::vector labelAttributes, std::string value, + std::vector valueAttributes, std::string increasedValue, + std::vector increasedValueAttributes, std::string decreasedValue, + std::vector decreasedValueAttributes, + std::string hint, + std::vector hintAttributes, int textDirection, const tonic::Float64List& transform, const tonic::Int32List& childrenInTraversalOrder, @@ -64,7 +72,6 @@ class SemanticsUpdateBuilder private: explicit SemanticsUpdateBuilder(); - SemanticsNodeUpdates nodes_; CustomAccessibilityActionUpdates actions_; }; diff --git a/engine/src/flutter/lib/ui/semantics/semantics_update_builder_unittests.cc b/engine/src/flutter/lib/ui/semantics/semantics_update_builder_unittests.cc new file mode 100644 index 0000000000..fd89d345d9 --- /dev/null +++ b/engine/src/flutter/lib/ui/semantics/semantics_update_builder_unittests.cc @@ -0,0 +1,93 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/lib/ui/semantics/semantics_update_builder.h" +#include "flutter/shell/common/shell_test.h" + +#include "gtest/gtest.h" + +namespace flutter { +namespace testing { + +using SemanticsUpdateBuilderTest = ShellTest; + +TEST_F(SemanticsUpdateBuilderTest, CanHandleAttributedStrings) { + auto message_latch = std::make_shared(); + + auto nativeSemanticsUpdate = [message_latch](Dart_NativeArguments args) { + auto handle = Dart_GetNativeArgument(args, 0); + intptr_t peer = 0; + Dart_Handle result = Dart_GetNativeInstanceField( + handle, tonic::DartWrappable::kPeerIndex, &peer); + ASSERT_FALSE(Dart_IsError(result)); + SemanticsUpdate* update = reinterpret_cast(peer); + SemanticsNodeUpdates nodes = update->takeNodes(); + ASSERT_EQ(nodes.size(), (size_t)1); + auto node = nodes.find(0)->second; + // Should match the updateNode in ui_test.dart. + ASSERT_EQ(node.label, "label"); + ASSERT_EQ(node.labelAttributes.size(), (size_t)1); + ASSERT_EQ(node.labelAttributes[0]->start, 1); + ASSERT_EQ(node.labelAttributes[0]->end, 2); + ASSERT_EQ(node.labelAttributes[0]->type, StringAttributeType::kSpellOut); + + ASSERT_EQ(node.value, "value"); + ASSERT_EQ(node.valueAttributes.size(), (size_t)1); + ASSERT_EQ(node.valueAttributes[0]->start, 2); + ASSERT_EQ(node.valueAttributes[0]->end, 3); + ASSERT_EQ(node.valueAttributes[0]->type, StringAttributeType::kSpellOut); + + ASSERT_EQ(node.hint, "hint"); + ASSERT_EQ(node.hintAttributes.size(), (size_t)1); + ASSERT_EQ(node.hintAttributes[0]->start, 0); + ASSERT_EQ(node.hintAttributes[0]->end, 1); + ASSERT_EQ(node.hintAttributes[0]->type, StringAttributeType::kLocale); + auto local_attribute = + std::static_pointer_cast(node.hintAttributes[0]); + ASSERT_EQ(local_attribute->locale, "en-MX"); + + ASSERT_EQ(node.increasedValue, "increasedValue"); + ASSERT_EQ(node.increasedValueAttributes.size(), (size_t)1); + ASSERT_EQ(node.increasedValueAttributes[0]->start, 4); + ASSERT_EQ(node.increasedValueAttributes[0]->end, 5); + ASSERT_EQ(node.increasedValueAttributes[0]->type, + StringAttributeType::kSpellOut); + + ASSERT_EQ(node.decreasedValue, "decreasedValue"); + ASSERT_EQ(node.decreasedValueAttributes.size(), (size_t)1); + ASSERT_EQ(node.decreasedValueAttributes[0]->start, 5); + ASSERT_EQ(node.decreasedValueAttributes[0]->end, 6); + ASSERT_EQ(node.decreasedValueAttributes[0]->type, + StringAttributeType::kSpellOut); + message_latch->Signal(); + }; + + Settings settings = CreateSettingsForFixture(); + TaskRunners task_runners("test", // label + GetCurrentTaskRunner(), // platform + CreateNewThread(), // raster + CreateNewThread(), // ui + CreateNewThread() // io + ); + + AddNativeCallback("SemanticsUpdate", + CREATE_NATIVE_ENTRY(nativeSemanticsUpdate)); + + std::unique_ptr shell = + CreateShell(std::move(settings), std::move(task_runners)); + + ASSERT_TRUE(shell->IsSetup()); + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("sendSemanticsUpdate"); + + shell->RunEngine(std::move(configuration), [](auto result) { + ASSERT_EQ(result, Engine::RunStatus::Success); + }); + + message_latch->Wait(); + DestroyShell(std::move(shell), std::move(task_runners)); +} + +} // namespace testing +} // namespace flutter diff --git a/engine/src/flutter/lib/ui/semantics/string_attribute.cc b/engine/src/flutter/lib/ui/semantics/string_attribute.cc new file mode 100644 index 0000000000..f1eac9c998 --- /dev/null +++ b/engine/src/flutter/lib/ui/semantics/string_attribute.cc @@ -0,0 +1,69 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/lib/ui/semantics/string_attribute.h" + +#include "flutter/fml/logging.h" +#include "flutter/lib/ui/ui_dart_state.h" +#include "third_party/tonic/dart_args.h" +#include "third_party/tonic/dart_binding_macros.h" + +#include + +namespace flutter { + +IMPLEMENT_WRAPPERTYPEINFO(ui, NativeStringAttribute); + +#define FOR_EACH_BINDING(V) \ + V(NativeStringAttribute, initLocaleStringAttribute) \ + V(NativeStringAttribute, initSpellOutStringAttribute) + +FOR_EACH_BINDING(DART_NATIVE_CALLBACK) + +void NativeStringAttribute::RegisterNatives( + tonic::DartLibraryNatives* natives) { + natives->Register({FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); +} + +NativeStringAttribute::NativeStringAttribute() {} + +NativeStringAttribute::~NativeStringAttribute() {} + +void NativeStringAttribute::initSpellOutStringAttribute( + Dart_Handle string_attribute_handle, + int32_t start, + int32_t end) { + UIDartState::ThrowIfUIOperationsProhibited(); + auto native_string_attribute = fml::MakeRefCounted(); + native_string_attribute->AssociateWithDartWrapper(string_attribute_handle); + + native_string_attribute->attribute_ = + std::make_shared(); + native_string_attribute->attribute_->start = start; + native_string_attribute->attribute_->end = end; + native_string_attribute->attribute_->type = StringAttributeType::kSpellOut; +} + +void NativeStringAttribute::initLocaleStringAttribute( + Dart_Handle string_attribute_handle, + int32_t start, + int32_t end, + std::string locale) { + UIDartState::ThrowIfUIOperationsProhibited(); + auto native_string_attribute = fml::MakeRefCounted(); + native_string_attribute->AssociateWithDartWrapper(string_attribute_handle); + + auto locale_attribute = std::make_shared(); + locale_attribute->start = start; + locale_attribute->end = end; + locale_attribute->type = StringAttributeType::kLocale; + locale_attribute->locale = locale; + native_string_attribute->attribute_ = locale_attribute; +} + +const StringAttributePtr NativeStringAttribute::GetAttribute() const { + return attribute_; +} + +} // namespace flutter diff --git a/engine/src/flutter/lib/ui/semantics/string_attribute.h b/engine/src/flutter/lib/ui/semantics/string_attribute.h new file mode 100644 index 0000000000..5fbcf84c0e --- /dev/null +++ b/engine/src/flutter/lib/ui/semantics/string_attribute.h @@ -0,0 +1,87 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_LIB_UI_SEMANTICS_STRING_ATTRIBUTE_H_ +#define FLUTTER_LIB_UI_SEMANTICS_STRING_ATTRIBUTE_H_ + +#include "flutter/lib/ui/dart_wrapper.h" +#include "third_party/tonic/dart_library_natives.h" + +namespace flutter { + +struct StringAttribute; + +using StringAttributePtr = std::shared_ptr; +using StringAttributes = std::vector; + +// When adding a new StringAttributeType, the classes in these file must be +// updated as well. +// * engine/src/flutter/lib/ui/semantics.dart +// * engine/src/flutter/lib/web_ui/lib/src/ui/semantics.dart +// * engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java + +enum class StringAttributeType : int32_t { + kSpellOut, + kLocale, +}; + +//------------------------------------------------------------------------------ +/// The c++ representation of the StringAttribute, this struct serves as an +/// abstract interface for the subclasses and should not be used directly. +struct StringAttribute { + virtual ~StringAttribute() = default; + int32_t start = -1; + int32_t end = -1; + StringAttributeType type; +}; + +//------------------------------------------------------------------------------ +/// Indicates the string needs to be spelled out character by character when the +/// assistive technologies announce the string. +struct SpellOutStringAttribute : StringAttribute {}; + +//------------------------------------------------------------------------------ +/// Indicates the string needs to be treated as a specific language when the +/// assistive technologies announce the string. +struct LocaleStringAttribute : StringAttribute { + std::string locale; +}; + +//------------------------------------------------------------------------------ +/// The peer class for all of the StringAttribute subclasses in semantics.dart. +class NativeStringAttribute + : public RefCountedDartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FML_FRIEND_MAKE_REF_COUNTED(NativeStringAttribute); + + public: + ~NativeStringAttribute() override; + + //---------------------------------------------------------------------------- + /// The init method for SpellOutStringAttribute constructor + static void initSpellOutStringAttribute(Dart_Handle string_attribute_handle, + int32_t start, + int32_t end); + + //---------------------------------------------------------------------------- + /// The init method for LocaleStringAttribute constructor + static void initLocaleStringAttribute(Dart_Handle string_attribute_handle, + int32_t start, + int32_t end, + std::string locale); + + //---------------------------------------------------------------------------- + /// Returns the c++ representataion of StringAttribute. + const StringAttributePtr GetAttribute() const; + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + NativeStringAttribute(); + StringAttributePtr attribute_; +}; + +} // namespace flutter + +#endif // FLUTTER_LIB_UI_SEMANTICS_STRING_ATTRIBUTE_H_ diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/semantics.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/semantics.dart index 032a88f997..dfda634c19 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/semantics.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/semantics.dart @@ -57,10 +57,15 @@ class SemanticsNodeUpdate { required this.scrollExtentMin, required this.rect, required this.label, + this.labelAttributes, required this.hint, + this.hintAttributes, required this.value, + this.valueAttributes, required this.increasedValue, + this.increasedValueAttributes, required this.decreasedValue, + this.decreasedValueAttributes, this.textDirection, required this.transform, required this.elevation, @@ -115,18 +120,33 @@ class SemanticsNodeUpdate { /// See [ui.SemanticsUpdateBuilder.updateNode]. final String label; + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final List? labelAttributes; + /// See [ui.SemanticsUpdateBuilder.updateNode]. final String hint; + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final List? hintAttributes; + /// See [ui.SemanticsUpdateBuilder.updateNode]. final String value; + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final List? valueAttributes; + /// See [ui.SemanticsUpdateBuilder.updateNode]. final String increasedValue; + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final List? increasedValueAttributes; + /// See [ui.SemanticsUpdateBuilder.updateNode]. final String decreasedValue; + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final List? decreasedValueAttributes; + /// See [ui.SemanticsUpdateBuilder.updateNode]. final ui.TextDirection? textDirection; @@ -401,6 +421,10 @@ class SemanticsObject { String? get label => _label; String? _label; + /// See [ui.SemanticsUpdateBuilder.updateNode] + List? get labelAttributes => _labelAttributes; + List? _labelAttributes; + /// Whether this object contains a non-empty label. bool get hasLabel => _label != null && _label!.isNotEmpty; @@ -417,6 +441,10 @@ class SemanticsObject { String? get hint => _hint; String? _hint; + /// See [ui.SemanticsUpdateBuilder.updateNode] + List? get hintAttributes => _hintAttributes; + List? _hintAttributes; + static const int _hintIndex = 1 << 11; /// Whether the [hint] field has been updated but has not been @@ -430,6 +458,10 @@ class SemanticsObject { String? get value => _value; String? _value; + /// See [ui.SemanticsUpdateBuilder.updateNode] + List? get valueAttributes => _valueAttributes; + List? _valueAttributes; + /// Whether this object contains a non-empty value. bool get hasValue => _value != null && _value!.isNotEmpty; @@ -446,6 +478,10 @@ class SemanticsObject { String? get increasedValue => _increasedValue; String? _increasedValue; + /// See [ui.SemanticsUpdateBuilder.updateNode] + List? get increasedValueAttributes => _increasedValueAttributes; + List? _increasedValueAttributes; + static const int _increasedValueIndex = 1 << 13; /// Whether the [increasedValue] field has been updated but has not been @@ -459,6 +495,10 @@ class SemanticsObject { String? get decreasedValue => _decreasedValue; String? _decreasedValue; + /// See [ui.SemanticsUpdateBuilder.updateNode] + List? get decreasedValueAttributes => _decreasedValueAttributes; + List? _decreasedValueAttributes; + static const int _decreasedValueIndex = 1 << 14; /// Whether the [decreasedValue] field has been updated but has not been @@ -652,11 +692,21 @@ class SemanticsObject { _markValueDirty(); } + if (_valueAttributes != update.valueAttributes) { + _valueAttributes = update.valueAttributes; + _markValueDirty(); + } + if (_label != update.label) { _label = update.label; _markLabelDirty(); } + if (_labelAttributes != update.labelAttributes) { + _labelAttributes = update.labelAttributes; + _markLabelDirty(); + } + if (_rect != update.rect) { _rect = update.rect; _markRectDirty(); @@ -712,16 +762,31 @@ class SemanticsObject { _markHintDirty(); } + if (_hintAttributes != update.hintAttributes) { + _hintAttributes = update.hintAttributes; + _markHintDirty(); + } + if (_increasedValue != update.increasedValue) { _increasedValue = update.increasedValue; _markIncreasedValueDirty(); } + if (_increasedValueAttributes != update.increasedValueAttributes) { + _increasedValueAttributes = update.increasedValueAttributes; + _markIncreasedValueDirty(); + } + if (_decreasedValue != update.decreasedValue) { _decreasedValue = update.decreasedValue; _markDecreasedValueDirty(); } + if (_decreasedValueAttributes != update.decreasedValueAttributes) { + _decreasedValueAttributes = update.decreasedValueAttributes; + _markDecreasedValueDirty(); + } + if (_textDirection != update.textDirection) { _textDirection = update.textDirection; _markTextDirectionDirty(); diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/semantics.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/semantics.dart index 4c351efafb..3fbb801486 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/semantics.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/semantics.dart @@ -275,6 +275,58 @@ class SemanticsFlag { } } + +// When adding a new StringAttributeType, the classes in these file must be +// updated as well. +// * engine/src/flutter/lib/ui/semantics.dart +// * engine/src/flutter/lib/ui/semantics/string_attribute.h +// * engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java + +abstract class StringAttribute { + StringAttribute._({ + required this.range, + }); + + final TextRange range; + + StringAttribute copy({required TextRange range}); +} + +class SpellOutStringAttribute extends StringAttribute { + SpellOutStringAttribute({ + required TextRange range, + }) : super._(range: range); + + @override + StringAttribute copy({required TextRange range}) { + return SpellOutStringAttribute(range: range); + } + + @override + String toString() { + return 'SpellOutStringAttribute(range: $range)'; + } +} + +class LocaleStringAttribute extends StringAttribute { + LocaleStringAttribute({ + required TextRange range, + required this.locale, + }) : super._(range: range); + + final Locale locale; + + @override + StringAttribute copy({required TextRange range}) { + return LocaleStringAttribute(range: range, locale: this.locale); + } + + @override + String toString() { + return 'LocaleStringAttribute(range: $range, locale: ${locale.toLanguageTag()})'; + } +} + class SemanticsUpdateBuilder { SemanticsUpdateBuilder(); @@ -297,10 +349,15 @@ class SemanticsUpdateBuilder { required double thickness, required Rect rect, required String label, - required String hint, + List? labelAttributes, required String value, + List? valueAttributes, required String increasedValue, + List? increasedValueAttributes, required String decreasedValue, + List? decreasedValueAttributes, + required String hint, + List? hintAttributes, TextDirection? textDirection, required Float64List transform, required Int32List childrenInTraversalOrder, @@ -324,10 +381,15 @@ class SemanticsUpdateBuilder { scrollExtentMin: scrollExtentMin, rect: rect, label: label, - hint: hint, + labelAttributes: labelAttributes, value: value, + valueAttributes: valueAttributes, increasedValue: increasedValue, + increasedValueAttributes: increasedValueAttributes, decreasedValue: decreasedValue, + decreasedValueAttributes: decreasedValueAttributes, + hint: hint, + hintAttributes: hintAttributes, textDirection: textDirection, transform: engine.toMatrix32(transform), elevation: elevation, 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 6b817e35aa..18d9d5ea44 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 @@ -609,10 +609,13 @@ public class FlutterJNI { */ @SuppressWarnings("unused") @UiThread - private void updateSemantics(@NonNull ByteBuffer buffer, @NonNull String[] strings) { + private void updateSemantics( + @NonNull ByteBuffer buffer, + @NonNull String[] strings, + @NonNull ByteBuffer[] stringAttributeArgs) { ensureRunningOnMainThread(); if (accessibilityDelegate != null) { - accessibilityDelegate.updateSemantics(buffer, strings); + accessibilityDelegate.updateSemantics(buffer, strings, stringAttributeArgs); } // TODO(mattcarroll): log dropped messages when in debug mode // (https://github.com/flutter/flutter/issues/25391) @@ -1256,7 +1259,10 @@ public class FlutterJNI { *

Implementers are expected to maintain an Android-side cache of Flutter's semantics tree. * This method provides updates from Flutter for the Android-side semantics tree cache. */ - void updateSemantics(@NonNull ByteBuffer buffer, @NonNull String[] strings); + void updateSemantics( + @NonNull ByteBuffer buffer, + @NonNull String[] strings, + @NonNull ByteBuffer[] stringAttributeArgs); } 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 3c02a901b3..bbba096bf6 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 @@ -15,6 +15,10 @@ import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; +import android.text.SpannableString; +import android.text.TextUtils; +import android.text.style.LocaleSpan; +import android.text.style.TtsSpan; import android.view.MotionEvent; import android.view.View; import android.view.WindowInsets; @@ -33,6 +37,7 @@ import io.flutter.plugin.platform.PlatformViewsAccessibilityDelegate; import io.flutter.util.Predicate; import java.nio.ByteBuffer; import java.nio.ByteOrder; +import java.nio.charset.Charset; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -272,9 +277,13 @@ public class AccessibilityBridge extends AccessibilityNodeProvider { /** Flutter's semantics tree has changed. Update our Android-side cache. */ @Override - public void updateSemantics(ByteBuffer buffer, String[] strings) { + public void updateSemantics( + ByteBuffer buffer, String[] strings, ByteBuffer[] stringAttributeArgs) { buffer.order(ByteOrder.LITTLE_ENDIAN); - AccessibilityBridge.this.updateSemantics(buffer, strings); + for (ByteBuffer args : stringAttributeArgs) { + args.order(ByteOrder.LITTLE_ENDIAN); + } + AccessibilityBridge.this.updateSemantics(buffer, strings, stringAttributeArgs); } }; @@ -810,7 +819,10 @@ public class AccessibilityBridge extends AccessibilityNodeProvider { if (semanticsNode.hasFlag(Flag.IS_TEXT_FIELD)) { result.setText(semanticsNode.getValueLabelHint()); } else if (!semanticsNode.hasFlag(Flag.SCOPES_ROUTE)) { - result.setContentDescription(semanticsNode.getValueLabelHint()); + CharSequence content = semanticsNode.getValueLabelHint(); + if (content != null) { + result.setContentDescription(content); + } } boolean hasCheckedState = semanticsNode.hasFlag(Flag.HAS_CHECKED_STATE); @@ -951,6 +963,7 @@ public class AccessibilityBridge extends AccessibilityNodeProvider { accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.SCROLL_LEFT); } else if (semanticsNode.hasAction(Action.INCREASE)) { semanticsNode.value = semanticsNode.increasedValue; + semanticsNode.valueAttributes = semanticsNode.increasedValueAttributes; // Event causes Android to read out the updated value. sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED); accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.INCREASE); @@ -968,6 +981,7 @@ public class AccessibilityBridge extends AccessibilityNodeProvider { accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.SCROLL_RIGHT); } else if (semanticsNode.hasAction(Action.DECREASE)) { semanticsNode.value = semanticsNode.decreasedValue; + semanticsNode.valueAttributes = semanticsNode.decreasedValueAttributes; // Event causes Android to read out the updated value. sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED); accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.DECREASE); @@ -1459,12 +1473,15 @@ public class AccessibilityBridge extends AccessibilityNodeProvider { * buffer is encoded by PlatformViewAndroid::UpdateSemantics, and the decode logic must be kept in * sync with that method's encoding logic. */ - void updateSemantics(@NonNull ByteBuffer buffer, @NonNull String[] strings) { + void updateSemantics( + @NonNull ByteBuffer buffer, + @NonNull String[] strings, + @NonNull ByteBuffer[] stringAttributeArgs) { ArrayList updated = new ArrayList<>(); while (buffer.hasRemaining()) { int id = buffer.getInt(); SemanticsNode semanticsNode = getOrCreateSemanticsNode(id); - semanticsNode.updateWith(buffer, strings); + semanticsNode.updateWith(buffer, strings, stringAttributeArgs); if (semanticsNode.hasFlag(Flag.IS_HIDDEN)) { continue; } @@ -2039,6 +2056,29 @@ public class AccessibilityBridge extends AccessibilityNodeProvider { private String hint; } + // When adding a new StringAttributeType, the classes in these file must be + // updated as well. + // * engine/src/flutter/lib/ui/semantics.dart + // * engine/src/flutter/lib/web_ui/lib/src/ui/semantics.dart + // * engine/src/flutter/lib/ui/semantics/string_attribute.h + + private enum StringAttributeType { + SPELLOUT, + LOCALE, + } + + private static class StringAttribute { + int start; + int end; + StringAttributeType type; + } + + private static class SpellOutStringAttribute extends StringAttribute {} + + private static class LocaleStringAttribute extends StringAttribute { + String locale; + } + /** * Flutter {@code SemanticsNode} represented in Java/Android. * @@ -2075,10 +2115,15 @@ public class AccessibilityBridge extends AccessibilityNodeProvider { private float scrollExtentMax; private float scrollExtentMin; private String label; + private List labelAttributes; private String value; + private List valueAttributes; private String increasedValue; + private List increasedValueAttributes; private String decreasedValue; + private List decreasedValueAttributes; private String hint; + private List hintAttributes; // The id of the sibling node that is before this node in traversal // order. @@ -2229,7 +2274,10 @@ public class AccessibilityBridge extends AccessibilityNodeProvider { } } - private void updateWith(@NonNull ByteBuffer buffer, @NonNull String[] strings) { + private void updateWith( + @NonNull ByteBuffer buffer, + @NonNull String[] strings, + @NonNull ByteBuffer[] stringAttributeArgs) { hadPreviousConfig = true; previousValue = value; previousLabel = label; @@ -2257,18 +2305,28 @@ public class AccessibilityBridge extends AccessibilityNodeProvider { int stringIndex = buffer.getInt(); label = stringIndex == -1 ? null : strings[stringIndex]; + labelAttributes = getStringAttributesFromBuffer(buffer, stringAttributeArgs); + stringIndex = buffer.getInt(); value = stringIndex == -1 ? null : strings[stringIndex]; + valueAttributes = getStringAttributesFromBuffer(buffer, stringAttributeArgs); + stringIndex = buffer.getInt(); increasedValue = stringIndex == -1 ? null : strings[stringIndex]; + increasedValueAttributes = getStringAttributesFromBuffer(buffer, stringAttributeArgs); + stringIndex = buffer.getInt(); decreasedValue = stringIndex == -1 ? null : strings[stringIndex]; + decreasedValueAttributes = getStringAttributesFromBuffer(buffer, stringAttributeArgs); + stringIndex = buffer.getInt(); hint = stringIndex == -1 ? null : strings[stringIndex]; + hintAttributes = getStringAttributesFromBuffer(buffer, stringAttributeArgs); + textDirection = TextDirection.fromInt(buffer.getInt()); left = buffer.getFloat(); @@ -2327,6 +2385,48 @@ public class AccessibilityBridge extends AccessibilityNodeProvider { } } + private List getStringAttributesFromBuffer( + @NonNull ByteBuffer buffer, @NonNull ByteBuffer[] stringAttributeArgs) { + final int attributesCount = buffer.getInt(); + if (attributesCount == -1) { + return null; + } + final List result = new ArrayList<>(attributesCount); + for (int i = 0; i < attributesCount; ++i) { + final int start = buffer.getInt(); + final int end = buffer.getInt(); + final StringAttributeType type = StringAttributeType.values()[buffer.getInt()]; + switch (type) { + case SPELLOUT: + { + // Pops the -1 size. + buffer.getInt(); + SpellOutStringAttribute attribute = new SpellOutStringAttribute(); + attribute.start = start; + attribute.end = end; + attribute.type = type; + result.add(attribute); + break; + } + case LOCALE: + { + final int argsIndex = buffer.getInt(); + final ByteBuffer args = stringAttributeArgs[argsIndex]; + LocaleStringAttribute attribute = new LocaleStringAttribute(); + attribute.start = start; + attribute.end = end; + attribute.type = type; + attribute.locale = Charset.forName("UTF-8").decode(args).toString(); + result.add(attribute); + break; + } + default: + break; + } + } + return result; + } + private void ensureInverseTransform() { if (!inverseTransformDirty) { return; @@ -2503,16 +2603,59 @@ public class AccessibilityBridge extends AccessibilityNodeProvider { return Math.max(a, Math.max(b, Math.max(c, d))); } - private String getValueLabelHint() { - StringBuilder sb = new StringBuilder(); - String[] array = {value, label, hint}; - for (String word : array) { + private CharSequence getValueLabelHint() { + CharSequence[] array; + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { + array = new CharSequence[] {value, label, hint}; + } else { + array = + new CharSequence[] { + createSpannableString(value, valueAttributes), + createSpannableString(label, labelAttributes), + createSpannableString(hint, hintAttributes), + }; + } + CharSequence result = null; + for (CharSequence word : array) { if (word != null && word.length() > 0) { - if (sb.length() > 0) sb.append(", "); - sb.append(word); + if (result == null || result.length() == 0) { + result = word; + } else { + result = TextUtils.concat(result, ", ", word); + } } } - return sb.length() > 0 ? sb.toString() : null; + return result; + } + + @TargetApi(21) + @RequiresApi(21) + private SpannableString createSpannableString(String string, List attributes) { + if (string == null) { + return null; + } + final SpannableString spannableString = new SpannableString(string); + if (attributes != null) { + for (StringAttribute attribute : attributes) { + switch (attribute.type) { + case SPELLOUT: + { + final TtsSpan ttsSpan = new TtsSpan.Builder(TtsSpan.TYPE_VERBATIM).build(); + spannableString.setSpan(ttsSpan, attribute.start, attribute.end, 0); + break; + } + case LOCALE: + { + LocaleStringAttribute localeAttribute = (LocaleStringAttribute) attribute; + Locale locale = Locale.forLanguageTag(localeAttribute.locale); + final LocaleSpan localeSpan = new LocaleSpan(locale); + spannableString.setSpan(localeSpan, attribute.start, attribute.end, 0); + break; + } + } + } + } + return spannableString; } } 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 1a31db796a..9b1e02ad71 100644 --- a/engine/src/flutter/shell/platform/android/jni/jni_mock.h +++ b/engine/src/flutter/shell/platform/android/jni/jni_mock.h @@ -29,7 +29,9 @@ class JNIMock final : public PlatformViewAndroidJNI { MOCK_METHOD(void, FlutterViewUpdateSemantics, - (std::vector buffer, std::vector strings), + (std::vector buffer, + std::vector strings, + std::vector> string_attribute_args), (override)); MOCK_METHOD(void, 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 eae098a6b8..f04d1c72fb 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 @@ -56,8 +56,10 @@ class PlatformViewAndroidJNI { /// /// @note Must be called from the platform thread. /// - virtual void FlutterViewUpdateSemantics(std::vector buffer, - std::vector strings) = 0; + virtual void FlutterViewUpdateSemantics( + std::vector buffer, + std::vector strings, + std::vector> string_attribute_args) = 0; //---------------------------------------------------------------------------- /// @brief Sends new custom accessibility events. diff --git a/engine/src/flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.cc b/engine/src/flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.cc index 9570d72c01..1f6522f86a 100644 --- a/engine/src/flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.cc +++ b/engine/src/flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.cc @@ -6,6 +6,35 @@ namespace flutter { +void putStringAttributesIntoBuffer( + const StringAttributes& attributes, + int32_t* buffer_int32, + size_t& position, + std::vector>& string_attribute_args) { + if (attributes.empty()) { + buffer_int32[position++] = -1; + return; + } + buffer_int32[position++] = attributes.size(); + for (const auto& attribute : attributes) { + buffer_int32[position++] = attribute->start; + buffer_int32[position++] = attribute->end; + buffer_int32[position++] = static_cast(attribute->type); + switch (attribute->type) { + case StringAttributeType::kSpellOut: + buffer_int32[position++] = -1; + break; + case StringAttributeType::kLocale: + buffer_int32[position++] = string_attribute_args.size(); + std::shared_ptr locale_attribute = + std::static_pointer_cast(attribute); + string_attribute_args.push_back( + {locale_attribute->locale.begin(), locale_attribute->locale.end()}); + break; + } + } +} + PlatformViewAndroidDelegate::PlatformViewAndroidDelegate( std::shared_ptr jni_facade) : jni_facade_(jni_facade){}; @@ -13,9 +42,11 @@ PlatformViewAndroidDelegate::PlatformViewAndroidDelegate( void PlatformViewAndroidDelegate::UpdateSemantics( flutter::SemanticsNodeUpdates update, flutter::CustomAccessibilityActionUpdates actions) { - constexpr size_t kBytesPerNode = 41 * sizeof(int32_t); + constexpr size_t kBytesPerNode = 46 * sizeof(int32_t); constexpr size_t kBytesPerChild = sizeof(int32_t); + constexpr size_t kBytesPerCustomAction = sizeof(int32_t); constexpr size_t kBytesPerAction = 4 * sizeof(int32_t); + constexpr size_t kBytesPerStringAttribute = 4 * sizeof(int32_t); { size_t num_bytes = 0; @@ -24,8 +55,18 @@ void PlatformViewAndroidDelegate::UpdateSemantics( num_bytes += value.second.childrenInTraversalOrder.size() * kBytesPerChild; num_bytes += value.second.childrenInHitTestOrder.size() * kBytesPerChild; + num_bytes += value.second.customAccessibilityActions.size() * + kBytesPerCustomAction; num_bytes += - value.second.customAccessibilityActions.size() * kBytesPerChild; + value.second.labelAttributes.size() * kBytesPerStringAttribute; + num_bytes += + value.second.valueAttributes.size() * kBytesPerStringAttribute; + num_bytes += value.second.increasedValueAttributes.size() * + kBytesPerStringAttribute; + num_bytes += value.second.decreasedValueAttributes.size() * + kBytesPerStringAttribute; + num_bytes += + value.second.hintAttributes.size() * kBytesPerStringAttribute; } // The encoding defined here is used in: // @@ -40,6 +81,7 @@ void PlatformViewAndroidDelegate::UpdateSemantics( float* buffer_float32 = reinterpret_cast(&buffer[0]); std::vector strings; + std::vector> string_attribute_args; size_t position = 0; for (const auto& value : update) { // If you edit this code, make sure you update kBytesPerNode @@ -65,30 +107,47 @@ void PlatformViewAndroidDelegate::UpdateSemantics( buffer_int32[position++] = strings.size(); strings.push_back(node.label); } + + putStringAttributesIntoBuffer(node.labelAttributes, buffer_int32, + position, string_attribute_args); if (node.value.empty()) { buffer_int32[position++] = -1; } else { buffer_int32[position++] = strings.size(); strings.push_back(node.value); } + + putStringAttributesIntoBuffer(node.valueAttributes, buffer_int32, + position, string_attribute_args); if (node.increasedValue.empty()) { buffer_int32[position++] = -1; } else { buffer_int32[position++] = strings.size(); strings.push_back(node.increasedValue); } + + putStringAttributesIntoBuffer(node.increasedValueAttributes, buffer_int32, + position, string_attribute_args); if (node.decreasedValue.empty()) { buffer_int32[position++] = -1; } else { buffer_int32[position++] = strings.size(); strings.push_back(node.decreasedValue); } + + putStringAttributesIntoBuffer(node.decreasedValueAttributes, buffer_int32, + position, string_attribute_args); + if (node.hint.empty()) { buffer_int32[position++] = -1; } else { buffer_int32[position++] = strings.size(); strings.push_back(node.hint); } + + putStringAttributesIntoBuffer(node.hintAttributes, buffer_int32, position, + string_attribute_args); + buffer_int32[position++] = node.textDirection; buffer_float32[position++] = node.rect.left(); buffer_float32[position++] = node.rect.top(); @@ -149,7 +208,8 @@ void PlatformViewAndroidDelegate::UpdateSemantics( } if (buffer.size() > 0) { - jni_facade_->FlutterViewUpdateSemantics(buffer, strings); + jni_facade_->FlutterViewUpdateSemantics(buffer, strings, + string_attribute_args); } } } diff --git a/engine/src/flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate_unittests.cc b/engine/src/flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate_unittests.cc index 9e1095ea6d..674544b176 100644 --- a/engine/src/flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate_unittests.cc +++ b/engine/src/flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate_unittests.cc @@ -21,7 +21,8 @@ TEST(PlatformViewShell, UpdateSemanticsDoesFlutterViewUpdateSemantics) { node0.label = "label"; update.insert(std::make_pair(0, std::move(node0))); - std::vector expected_buffer(164); + std::vector expected_buffer(184); + std::vector> expected_string_attribute_args(0); size_t position = 0; int32_t* buffer_int32 = reinterpret_cast(&expected_buffer[0]); float* buffer_float32 = reinterpret_cast(&expected_buffer[0]); @@ -41,10 +42,15 @@ TEST(PlatformViewShell, UpdateSemanticsDoesFlutterViewUpdateSemantics) { buffer_float32[position++] = static_cast(node0.scrollExtentMin); buffer_int32[position++] = expected_strings.size(); // node0.label expected_strings.push_back(node0.label); + buffer_int32[position++] = -1; // node0.labelAttributes buffer_int32[position++] = -1; // node0.value + buffer_int32[position++] = -1; // node0.valueAttributes buffer_int32[position++] = -1; // node0.increasedValue + buffer_int32[position++] = -1; // node0.increasedValueAttributes buffer_int32[position++] = -1; // node0.decreasedValue + buffer_int32[position++] = -1; // node0.decreasedValueAttributes buffer_int32[position++] = -1; // node0.hint + buffer_int32[position++] = -1; // node0.hintAttributes buffer_int32[position++] = node0.textDirection; buffer_float32[position++] = node0.rect.left(); buffer_float32[position++] = node0.rect.top(); @@ -54,9 +60,93 @@ TEST(PlatformViewShell, UpdateSemanticsDoesFlutterViewUpdateSemantics) { position += 16; buffer_int32[position++] = 0; // node0.childrenInTraversalOrder.size(); buffer_int32[position++] = 0; // node0.customAccessibilityActions.size(); - EXPECT_CALL(*jni_mock, - FlutterViewUpdateSemantics(expected_buffer, expected_strings)); + FlutterViewUpdateSemantics(expected_buffer, expected_strings, + expected_string_attribute_args)); + // Creates empty custom actions. + flutter::CustomAccessibilityActionUpdates actions; + delegate->UpdateSemantics(update, actions); +} + +TEST(PlatformViewShell, + UpdateSemanticsDoesFlutterViewUpdateSemanticsWithStringAttribtes) { + auto jni_mock = std::make_shared(); + auto delegate = std::make_unique(jni_mock); + + flutter::SemanticsNodeUpdates update; + flutter::SemanticsNode node0; + std::shared_ptr spell_out_attribute = + std::make_shared(); + spell_out_attribute->start = 2; + spell_out_attribute->end = 4; + spell_out_attribute->type = flutter::StringAttributeType::kSpellOut; + std::shared_ptr locale_attribute = + std::make_shared(); + locale_attribute->start = 1; + locale_attribute->end = 3; + locale_attribute->type = flutter::StringAttributeType::kLocale; + locale_attribute->locale = "en-US"; + node0.id = 0; + node0.label = "label"; + node0.labelAttributes.push_back(spell_out_attribute); + node0.hint = "hint"; + node0.hintAttributes.push_back(locale_attribute); + update.insert(std::make_pair(0, std::move(node0))); + + std::vector expected_buffer(216); + std::vector> expected_string_attribute_args; + size_t position = 0; + int32_t* buffer_int32 = reinterpret_cast(&expected_buffer[0]); + float* buffer_float32 = reinterpret_cast(&expected_buffer[0]); + std::vector expected_strings; + buffer_int32[position++] = node0.id; + buffer_int32[position++] = node0.flags; + buffer_int32[position++] = node0.actions; + buffer_int32[position++] = node0.maxValueLength; + buffer_int32[position++] = node0.currentValueLength; + buffer_int32[position++] = node0.textSelectionBase; + buffer_int32[position++] = node0.textSelectionExtent; + buffer_int32[position++] = node0.platformViewId; + buffer_int32[position++] = node0.scrollChildren; + buffer_int32[position++] = node0.scrollIndex; + buffer_float32[position++] = static_cast(node0.scrollPosition); + buffer_float32[position++] = static_cast(node0.scrollExtentMax); + buffer_float32[position++] = static_cast(node0.scrollExtentMin); + buffer_int32[position++] = expected_strings.size(); // node0.label + expected_strings.push_back(node0.label); + buffer_int32[position++] = 1; // node0.labelAttributes + buffer_int32[position++] = 2; // node0.labelAttributes[0].start + buffer_int32[position++] = 4; // node0.labelAttributes[0].end + buffer_int32[position++] = 0; // node0.labelAttributes[0].type + buffer_int32[position++] = -1; // node0.labelAttributes[0].args + buffer_int32[position++] = -1; // node0.value + buffer_int32[position++] = -1; // node0.valueAttributes + buffer_int32[position++] = -1; // node0.increasedValue + buffer_int32[position++] = -1; // node0.increasedValueAttributes + buffer_int32[position++] = -1; // node0.decreasedValue + buffer_int32[position++] = -1; // node0.decreasedValueAttributes + buffer_int32[position++] = expected_strings.size(); // node0.hint + expected_strings.push_back(node0.hint); + buffer_int32[position++] = 1; // node0.hintAttributes + buffer_int32[position++] = 1; // node0.hintAttributes[0].start + buffer_int32[position++] = 3; // node0.hintAttributes[0].end + buffer_int32[position++] = 1; // node0.hintAttributes[0].type + buffer_int32[position++] = + expected_string_attribute_args.size(); // node0.labelAttributes[0].args + expected_string_attribute_args.push_back( + {locale_attribute->locale.begin(), locale_attribute->locale.end()}); + buffer_int32[position++] = node0.textDirection; + buffer_float32[position++] = node0.rect.left(); + buffer_float32[position++] = node0.rect.top(); + buffer_float32[position++] = node0.rect.right(); + buffer_float32[position++] = node0.rect.bottom(); + node0.transform.getColMajor(&buffer_float32[position]); + position += 16; + buffer_int32[position++] = 0; // node0.childrenInTraversalOrder.size(); + buffer_int32[position++] = 0; // node0.customAccessibilityActions.size(); + EXPECT_CALL(*jni_mock, + FlutterViewUpdateSemantics(expected_buffer, expected_strings, + expected_string_attribute_args)); // Creates empty custom actions. flutter::CustomAccessibilityActionUpdates actions; delegate->UpdateSemantics(update, actions); 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 dc0cc7ec39..2a178b2162 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 @@ -844,9 +844,9 @@ bool RegisterApi(JNIEnv* env) { return false; } - g_update_semantics_method = - env->GetMethodID(g_flutter_jni_class->obj(), "updateSemantics", - "(Ljava/nio/ByteBuffer;[Ljava/lang/String;)V"); + g_update_semantics_method = env->GetMethodID( + g_flutter_jni_class->obj(), "updateSemantics", + "(Ljava/nio/ByteBuffer;[Ljava/lang/String;[Ljava/nio/ByteBuffer;)V"); if (g_update_semantics_method == nullptr) { FML_LOG(ERROR) << "Could not locate updateSemantics method"; @@ -1155,7 +1155,8 @@ void PlatformViewAndroidJNIImpl::FlutterViewHandlePlatformMessageResponse( void PlatformViewAndroidJNIImpl::FlutterViewUpdateSemantics( std::vector buffer, - std::vector strings) { + std::vector strings, + std::vector> string_attribute_args) { JNIEnv* env = fml::jni::AttachCurrentThread(); auto java_object = java_object_.get(env); @@ -1167,9 +1168,12 @@ void PlatformViewAndroidJNIImpl::FlutterViewUpdateSemantics( env, env->NewDirectByteBuffer(buffer.data(), buffer.size())); fml::jni::ScopedJavaLocalRef jstrings = fml::jni::VectorToStringArray(env, strings); + fml::jni::ScopedJavaLocalRef jstring_attribute_args = + fml::jni::VectorToBufferArray(env, string_attribute_args); env->CallVoidMethod(java_object.obj(), g_update_semantics_method, - direct_buffer.obj(), jstrings.obj()); + direct_buffer.obj(), jstrings.obj(), + jstring_attribute_args.obj()); FML_CHECK(CheckException(env)); } 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 34b80f07c6..3c8e60f72c 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 @@ -28,8 +28,10 @@ class PlatformViewAndroidJNIImpl final : public PlatformViewAndroidJNI { int responseId, std::unique_ptr data) override; - void FlutterViewUpdateSemantics(std::vector buffer, - std::vector strings) override; + void FlutterViewUpdateSemantics( + std::vector buffer, + std::vector strings, + std::vector> string_attribute_args) override; void FlutterViewUpdateCustomAccessibilityActions( std::vector actions_buffer, 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 b6c9ede5cc..93f62b6e2b 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 @@ -24,6 +24,9 @@ import android.content.ContentResolver; import android.content.Context; import android.graphics.Rect; import android.os.Bundle; +import android.text.SpannedString; +import android.text.style.LocaleSpan; +import android.text.style.TtsSpan; import android.view.MotionEvent; import android.view.View; import android.view.ViewParent; @@ -33,6 +36,7 @@ import android.view.accessibility.AccessibilityNodeInfo; import io.flutter.embedding.engine.systemchannels.AccessibilityChannel; import io.flutter.plugin.platform.PlatformViewsAccessibilityDelegate; import java.nio.ByteBuffer; +import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.junit.Test; @@ -54,11 +58,10 @@ public class AccessibilityBridgeTest { TestSemanticsNode testSemanticsNode = new TestSemanticsNode(); testSemanticsNode.label = "Hello, World"; TestSemanticsUpdate testSemanticsUpdate = testSemanticsNode.toUpdate(); - - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); - assertEquals(nodeInfo.getContentDescription(), "Hello, World"); + assertEquals(nodeInfo.getContentDescription().toString(), "Hello, World"); assertEquals(nodeInfo.getText(), null); } @@ -70,12 +73,11 @@ public class AccessibilityBridgeTest { testSemanticsNode.label = "Hello, World"; testSemanticsNode.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); TestSemanticsUpdate testSemanticsUpdate = testSemanticsNode.toUpdate(); - - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); assertEquals(nodeInfo.getContentDescription(), null); - assertEquals(nodeInfo.getText(), "Hello, World"); + assertEquals(nodeInfo.getText().toString(), "Hello, World"); } @Test @@ -104,7 +106,7 @@ public class AccessibilityBridgeTest { TestSemanticsNode testSemanticsNode = new TestSemanticsNode(); TestSemanticsUpdate testSemanticsUpdate = testSemanticsNode.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); Rect outBoundsInScreen = new Rect(); @@ -122,7 +124,7 @@ public class AccessibilityBridgeTest { testSemanticsNode.addFlag(AccessibilityBridge.Flag.SCOPES_ROUTE); TestSemanticsUpdate testSemanticsUpdate = testSemanticsNode.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); assertEquals(nodeInfo.getContentDescription(), null); @@ -148,7 +150,7 @@ public class AccessibilityBridgeTest { platformView.platformViewId = 42; root.children.add(platformView); TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); // Set a11y focus to platform view. View mockView = mock(View.class); @@ -168,7 +170,7 @@ public class AccessibilityBridgeTest { when(mockManager.isEnabled()).thenReturn(true); ViewParent mockParent = mock(ViewParent.class); when(mockRootView.getParent()).thenReturn(mockParent); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); // Check that unfocus event was sent. ArgumentCaptor eventCaptor = @@ -202,7 +204,7 @@ public class AccessibilityBridgeTest { node1.label = "node1"; root.children.add(node1); TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); ArgumentCaptor eventCaptor = ArgumentCaptor.forClass(AccessibilityEvent.class); @@ -229,7 +231,7 @@ public class AccessibilityBridgeTest { new_node2.label = "new_node2"; new_node1.children.add(new_node2); testSemanticsUpdate = new_root.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); eventCaptor = ArgumentCaptor.forClass(AccessibilityEvent.class); verify(mockParent, times(4)) @@ -266,7 +268,7 @@ public class AccessibilityBridgeTest { node2.label = "node2"; root.children.add(node2); TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); AccessibilityBridge spyAccessibilityBridge = spy(accessibilityBridge); AccessibilityNodeInfo mockNodeInfo2 = mock(AccessibilityNodeInfo.class); @@ -315,7 +317,7 @@ public class AccessibilityBridgeTest { child.right = 20; root.children.add(child); TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); ArgumentCaptor eventCaptor = ArgumentCaptor.forClass(AccessibilityEvent.class); @@ -370,7 +372,7 @@ public class AccessibilityBridgeTest { node2.label = "node2"; node1.children.add(node2); TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); ArgumentCaptor eventCaptor = ArgumentCaptor.forClass(AccessibilityEvent.class); @@ -395,7 +397,7 @@ public class AccessibilityBridgeTest { new_node2.label = "new_node2"; new_node1.children.add(new_node2); testSemanticsUpdate = new_root.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); eventCaptor = ArgumentCaptor.forClass(AccessibilityEvent.class); verify(mockParent, times(4)) @@ -437,7 +439,7 @@ public class AccessibilityBridgeTest { node1.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); root.children.add(node1); TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); Bundle bundle = new Bundle(); String expectedText = "some string"; bundle.putString(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, expectedText); @@ -476,13 +478,79 @@ public class AccessibilityBridgeTest { node1.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); root.children.add(node1); TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); Bundle bundle = new Bundle(); String expectedText = "some string"; bundle.putString(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, expectedText); accessibilityBridge.performAction(1, AccessibilityNodeInfo.ACTION_SET_TEXT, bundle); AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(1); - assertEquals(nodeInfo.getText(), expectedText); + assertEquals(nodeInfo.getText().toString(), expectedText); + } + + @TargetApi(21) + @Test + public void itBuildsAttributedString() { + 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"; + TestStringAttribute attribute = new TestStringAttributeSpellOut(); + attribute.start = 1; + attribute.end = 2; + attribute.type = TestStringAttributeType.SPELLOUT; + root.labelAttributes = + new ArrayList() { + { + add(attribute); + } + }; + root.value = "value"; + TestStringAttributeLocale localeAttribute = new TestStringAttributeLocale(); + localeAttribute.start = 1; + localeAttribute.end = 2; + localeAttribute.type = TestStringAttributeType.LOCALE; + localeAttribute.locale = "es-MX"; + root.valueAttributes = + new ArrayList() { + { + add(localeAttribute); + } + }; + + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + SpannedString actual = (SpannedString) nodeInfo.getContentDescription(); + assertEquals(actual.toString(), "value, label"); + Object[] objectSpans = actual.getSpans(0, actual.length(), Object.class); + assertEquals(objectSpans.length, 2); + LocaleSpan localeSpan = (LocaleSpan) objectSpans[0]; + assertEquals(localeSpan.getLocale().toLanguageTag(), "es-MX"); + assertEquals(actual.getSpanStart(localeSpan), 1); + assertEquals(actual.getSpanEnd(localeSpan), 2); + TtsSpan spellOutSpan = (TtsSpan) objectSpans[1]; + assertEquals(spellOutSpan.getType(), TtsSpan.TYPE_VERBATIM); + assertEquals(actual.getSpanStart(spellOutSpan), 8); + assertEquals(actual.getSpanEnd(spellOutSpan), 9); } @TargetApi(21) @@ -516,7 +584,7 @@ public class AccessibilityBridgeTest { node1.addAction(AccessibilityBridge.Action.SET_TEXT); root.children.add(node1); TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(1); List actions = nodeInfo.getActionList(); assertTrue(actions.contains(AccessibilityNodeInfo.AccessibilityAction.ACTION_SET_TEXT)); @@ -554,7 +622,7 @@ public class AccessibilityBridgeTest { node1.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); root.children.add(node1); TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); Bundle bundle = new Bundle(); int expectedStart = 1; int expectedEnd = 3; @@ -598,7 +666,7 @@ public class AccessibilityBridgeTest { node1.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); root.children.add(node1); TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); Bundle bundle = new Bundle(); bundle.putInt( AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, @@ -656,7 +724,7 @@ public class AccessibilityBridgeTest { node1.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); root.children.add(node1); TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); Bundle bundle = new Bundle(); bundle.putInt( AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, @@ -715,7 +783,7 @@ public class AccessibilityBridgeTest { node1.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); root.children.add(node1); TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); Bundle bundle = new Bundle(); bundle.putInt( AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, @@ -773,7 +841,7 @@ public class AccessibilityBridgeTest { node1.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); root.children.add(node1); TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); Bundle bundle = new Bundle(); bundle.putInt( AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, @@ -819,7 +887,7 @@ public class AccessibilityBridgeTest { scopeRoute.addFlag(AccessibilityBridge.Flag.SCOPES_ROUTE); root.children.add(scopeRoute); TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); ArgumentCaptor eventCaptor = ArgumentCaptor.forClass(AccessibilityEvent.class); @@ -852,7 +920,7 @@ public class AccessibilityBridgeTest { platformView.platformViewId = 42; root.children.add(platformView); TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); // Pass an out of bounds MotionEvent. accessibilityBridge.onAccessibilityHoverEvent(MotionEvent.obtain(1, 1, 1, -10, -10, 0)); @@ -884,12 +952,10 @@ public class AccessibilityBridgeTest { root.addChild(platformView); TestSemanticsUpdate testSemanticsRootUpdate = root.toUpdate(); - accessibilityBridge.updateSemantics( - testSemanticsRootUpdate.buffer, testSemanticsRootUpdate.strings); + testSemanticsRootUpdate.sendUpdateToBridge(accessibilityBridge); TestSemanticsUpdate testSemanticsPlatformViewUpdate = platformView.toUpdate(); - accessibilityBridge.updateSemantics( - testSemanticsPlatformViewUpdate.buffer, testSemanticsPlatformViewUpdate.strings); + testSemanticsPlatformViewUpdate.sendUpdateToBridge(accessibilityBridge); View embeddedView = mock(View.class); when(accessibilityDelegate.getPlatformViewById(1)).thenReturn(embeddedView); @@ -934,8 +1000,7 @@ public class AccessibilityBridgeTest { when(accessibilityDelegate.usesVirtualDisplay(1)).thenReturn(false); TestSemanticsUpdate testSemanticsRootUpdate = root.toUpdate(); - accessibilityBridge.updateSemantics( - testSemanticsRootUpdate.buffer, testSemanticsRootUpdate.strings); + testSemanticsRootUpdate.sendUpdateToBridge(accessibilityBridge); verify(embeddedView).setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO); } @@ -970,17 +1035,13 @@ public class AccessibilityBridgeTest { when(accessibilityDelegate.usesVirtualDisplay(1)).thenReturn(false); TestSemanticsUpdate testSemanticsRootWithPlatformViewUpdate = rootWithPlatformView.toUpdate(); - accessibilityBridge.updateSemantics( - testSemanticsRootWithPlatformViewUpdate.buffer, - testSemanticsRootWithPlatformViewUpdate.strings); + testSemanticsRootWithPlatformViewUpdate.sendUpdateToBridge(accessibilityBridge); TestSemanticsNode rootWithoutPlatformView = new TestSemanticsNode(); rootWithoutPlatformView.id = 0; TestSemanticsUpdate testSemanticsRootWithoutPlatformViewUpdate = rootWithoutPlatformView.toUpdate(); - accessibilityBridge.updateSemantics( - testSemanticsRootWithoutPlatformViewUpdate.buffer, - testSemanticsRootWithoutPlatformViewUpdate.strings); + testSemanticsRootWithoutPlatformViewUpdate.sendUpdateToBridge(accessibilityBridge); verify(embeddedView) .setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); @@ -1004,7 +1065,7 @@ public class AccessibilityBridgeTest { platformView.platformViewId = 1; TestSemanticsUpdate testSemanticsUpdate = platformView.toUpdate(); - accessibilityBridge.updateSemantics(testSemanticsUpdate.buffer, testSemanticsUpdate.strings); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); View embeddedView = mock(View.class); when(accessibilityDelegate.getPlatformViewById(1)).thenReturn(embeddedView); @@ -1091,13 +1152,46 @@ public class AccessibilityBridgeTest { /// The encoding for semantics is described in platform_view_android.cc class TestSemanticsUpdate { - TestSemanticsUpdate(ByteBuffer buffer, String[] strings) { + TestSemanticsUpdate(ByteBuffer buffer, String[] strings, ByteBuffer[] stringAttributeArgs) { this.buffer = buffer; this.strings = strings; + this.stringAttributeArgs = stringAttributeArgs; + } + + void sendUpdateToBridge(AccessibilityBridge bridge) { + bridge.updateSemantics(buffer, strings, stringAttributeArgs); } final ByteBuffer buffer; final String[] strings; + final ByteBuffer[] stringAttributeArgs; + } + + enum TestStringAttributeType { + SPELLOUT(0), + LOCALE(1); + + private final int value; + + private TestStringAttributeType(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + } + + class TestStringAttribute { + int start; + int end; + TestStringAttributeType type; + } + + class TestStringAttributeSpellOut extends TestStringAttribute {} + + class TestStringAttributeLocale extends TestStringAttribute { + String locale; } class TestSemanticsNode { @@ -1127,10 +1221,15 @@ public class AccessibilityBridgeTest { float scrollExtentMax = 0.0f; float scrollExtentMin = 0.0f; String label = null; + List labelAttributes; String value = null; + List valueAttributes; String increasedValue = null; + List increasedValueAttributes; String decreasedValue = null; + List decreasedValueAttributes; String hint = null; + List hintAttributes; int textDirection = 0; float left = 0.0f; float top = 0.0f; @@ -1146,12 +1245,17 @@ public class AccessibilityBridgeTest { TestSemanticsUpdate toUpdate() { ArrayList strings = new ArrayList(); ByteBuffer bytes = ByteBuffer.allocate(1000); - addToBuffer(bytes, strings); + ArrayList stringAttributeArgs = new ArrayList(); + addToBuffer(bytes, strings, stringAttributeArgs); bytes.flip(); - return new TestSemanticsUpdate(bytes, strings.toArray(new String[strings.size()])); + return new TestSemanticsUpdate( + bytes, + strings.toArray(new String[strings.size()]), + stringAttributeArgs.toArray(new ByteBuffer[stringAttributeArgs.size()])); } - protected void addToBuffer(ByteBuffer bytes, ArrayList strings) { + protected void addToBuffer( + ByteBuffer bytes, ArrayList strings, ArrayList stringAttributeArgs) { bytes.putInt(id); bytes.putInt(flags); bytes.putInt(actions); @@ -1165,11 +1269,11 @@ public class AccessibilityBridgeTest { bytes.putFloat(scrollPosition); bytes.putFloat(scrollExtentMax); bytes.putFloat(scrollExtentMin); - updateString(label, bytes, strings); - updateString(value, bytes, strings); - updateString(increasedValue, bytes, strings); - updateString(decreasedValue, bytes, strings); - updateString(hint, bytes, strings); + updateString(label, labelAttributes, bytes, strings, stringAttributeArgs); + updateString(value, valueAttributes, bytes, strings, stringAttributeArgs); + updateString(increasedValue, increasedValueAttributes, bytes, strings, stringAttributeArgs); + updateString(decreasedValue, decreasedValueAttributes, bytes, strings, stringAttributeArgs); + updateString(hint, hintAttributes, bytes, strings, stringAttributeArgs); bytes.putInt(textDirection); bytes.putFloat(left); bytes.putFloat(top); @@ -1192,17 +1296,43 @@ public class AccessibilityBridgeTest { bytes.putInt(0); // child nodes for (TestSemanticsNode node : children) { - node.addToBuffer(bytes, strings); + node.addToBuffer(bytes, strings, stringAttributeArgs); } } } - static void updateString(String value, ByteBuffer bytes, ArrayList strings) { + static void updateString( + String value, + List attributes, + ByteBuffer bytes, + ArrayList strings, + ArrayList stringAttributeArgs) { if (value == null) { bytes.putInt(-1); } else { strings.add(value); bytes.putInt(strings.size() - 1); } + // attributes + if (attributes == null || attributes.isEmpty()) { + bytes.putInt(-1); + return; + } + bytes.putInt(attributes.size()); + for (TestStringAttribute attribute : attributes) { + bytes.putInt(attribute.start); + bytes.putInt(attribute.end); + bytes.putInt(attribute.type.getValue()); + switch (attribute.type) { + case SPELLOUT: + bytes.putInt(-1); + break; + case LOCALE: + bytes.putInt(stringAttributeArgs.size()); + TestStringAttributeLocale localeAttribute = (TestStringAttributeLocale) attribute; + stringAttributeArgs.add(Charset.forName("UTF-8").encode(localeAttribute.locale)); + break; + } + } } } diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h index e9219d724d..15a77c3efe 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h @@ -43,27 +43,11 @@ constexpr int32_t kRootNodeId = 0; */ @property(nonatomic, readonly) fml::WeakPtr bridge; -/** - * Due to the fact that VoiceOver may hold onto SemanticObjects even after it shuts down, - * there can be situations where the AccessibilityBridge is shutdown, but the SemanticObject - * will still be alive. If VoiceOver is turned on again, it may try to access this orphaned - * SemanticObject. Methods that are called from the accessiblity framework should use - * this to guard against this case by just returning early if its bridge has been shutdown. - * - * See https://github.com/flutter/flutter/issues/43795 for more information. - */ -- (BOOL)isAccessibilityBridgeAlive; - /** * The semantics node used to produce this semantics object. */ @property(nonatomic, readonly) flutter::SemanticsNode node; -/** - * Updates this semantics object using data from the `node` argument. - */ -- (void)setSemanticsNode:(const flutter::SemanticsNode*)node NS_REQUIRES_SUPER; - /** * Whether this semantics object has child semantics objects. */ @@ -80,22 +64,42 @@ constexpr int32_t kRootNodeId = 0; */ @property(strong, nonatomic) FlutterPlatformViewSemanticsContainer* platformViewSemanticsContainer; +/** + * Due to the fact that VoiceOver may hold onto SemanticObjects even after it shuts down, + * there can be situations where the AccessibilityBridge is shutdown, but the SemanticObject + * will still be alive. If VoiceOver is turned on again, it may try to access this orphaned + * SemanticObject. Methods that are called from the accessiblity framework should use + * this to guard against this case by just returning early if its bridge has been shutdown. + * + * See https://github.com/flutter/flutter/issues/43795 for more information. + */ +- (BOOL)isAccessibilityBridgeAlive; + +/** + * Updates this semantics object using data from the `node` argument. + */ +- (void)setSemanticsNode:(const flutter::SemanticsNode*)node NS_REQUIRES_SUPER; + - (void)replaceChildAtIndex:(NSInteger)index withChild:(SemanticsObject*)child; - (BOOL)nodeWillCauseLayoutChange:(const flutter::SemanticsNode*)node; +- (BOOL)nodeWillCauseScroll:(const flutter::SemanticsNode*)node; + +- (BOOL)nodeShouldTriggerAnnouncement:(const flutter::SemanticsNode*)node; + +- (void)collectRoutes:(NSMutableArray*)edges; + +- (NSString*)routeName; + +- (BOOL)onCustomAccessibilityAction:(FlutterCustomAccessibilityAction*)action; + #pragma mark - Designated initializers - (instancetype)init __attribute__((unavailable("Use initWithBridge instead"))); - (instancetype)initWithBridge:(fml::WeakPtr)bridge uid:(int32_t)uid NS_DESIGNATED_INITIALIZER; -- (BOOL)nodeWillCauseScroll:(const flutter::SemanticsNode*)node; -- (BOOL)nodeShouldTriggerAnnouncement:(const flutter::SemanticsNode*)node; -- (void)collectRoutes:(NSMutableArray*)edges; -- (NSString*)routeName; -- (BOOL)onCustomAccessibilityAction:(FlutterCustomAccessibilityAction*)action; - @end /** 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 271e576ec5..a0748e37c8 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 @@ -144,7 +144,27 @@ flutter::SemanticsAction GetSemanticsActionForScrollDirection( [super dealloc]; } -#pragma mark - Semantic object methods +#pragma mark - Semantic object property accesser + +- (void)setChildren:(NSArray*)children { + for (SemanticsObject* child in _children) { + [child privateSetParent:nil]; + } + [_children release]; + _children = [[NSMutableArray alloc] initWithArray:children]; + for (SemanticsObject* child in _children) { + [child privateSetParent:self]; + } +} + +- (BOOL)hasChildren { + if (_node.IsPlatformViewNode()) { + return YES; + } + return [self.children count] != 0; +} + +#pragma mark - Semantic object method - (BOOL)isAccessibilityBridgeAlive { return [self bridge].get() != nil; @@ -188,28 +208,6 @@ flutter::SemanticsAction GetSemanticsActionForScrollDirection( return [self node].label != node->label; } -- (BOOL)hasChildren { - if (_node.IsPlatformViewNode()) { - return YES; - } - return [self.children count] != 0; -} - -- (void)privateSetParent:(SemanticsObject*)parent { - _parent = parent; -} - -- (void)setChildren:(NSArray*)children { - for (SemanticsObject* child in _children) { - [child privateSetParent:nil]; - } - [_children release]; - _children = [[NSMutableArray alloc] initWithArray:children]; - for (SemanticsObject* child in _children) { - [child privateSetParent:self]; - } -} - - (void)replaceChildAtIndex:(NSInteger)index withChild:(SemanticsObject*)child { SemanticsObject* oldChild = _children[index]; [oldChild privateSetParent:nil]; @@ -217,6 +215,63 @@ flutter::SemanticsAction GetSemanticsActionForScrollDirection( [_children replaceObjectAtIndex:index withObject:child]; } +- (NSString*)routeName { + // Returns the first non-null and non-empty semantic label of a child + // with an NamesRoute flag. Otherwise returns nil. + if ([self node].HasFlag(flutter::SemanticsFlags::kNamesRoute)) { + NSString* newName = [self accessibilityLabel]; + if (newName != nil && [newName length] > 0) { + return newName; + } + } + if ([self hasChildren]) { + for (SemanticsObject* child in self.children) { + NSString* newName = [child routeName]; + if (newName != nil && [newName length] > 0) { + return newName; + } + } + } + return nil; +} + +#pragma mark - Semantic object private method + +- (void)privateSetParent:(SemanticsObject*)parent { + _parent = parent; +} + +- (NSAttributedString*)createAttributedStringFromString:(NSString*)string + withAttributes: + (const flutter::StringAttributes&)attributes { + NSMutableAttributedString* attributedString = + [[NSMutableAttributedString alloc] initWithString:string]; + for (const auto& attribute : attributes) { + NSRange range = NSMakeRange(attribute->start, attribute->end - attribute->start); + switch (attribute->type) { + case flutter::StringAttributeType::kLocale: { + std::shared_ptr locale_attribute = + std::static_pointer_cast(attribute); + NSDictionary* attributeDict = @{ + UIAccessibilitySpeechAttributeLanguage : @(locale_attribute->locale.data()), + }; + [attributedString setAttributes:attributeDict range:range]; + break; + } + case flutter::StringAttributeType::kSpellOut: { + if (@available(iOS 13.0, *)) { + NSDictionary* attributeDict = @{ + UIAccessibilitySpeechAttributeSpellOut : @YES, + }; + [attributedString setAttributes:attributeDict range:range]; + } + break; + } + } + } + return attributedString; +} + #pragma mark - UIAccessibility overrides - (BOOL)isAccessibilityElement { @@ -271,26 +326,6 @@ flutter::SemanticsAction GetSemanticsActionForScrollDirection( return YES; } -- (NSString*)routeName { - // Returns the first non-null and non-empty semantic label of a child - // with an NamesRoute flag. Otherwise returns nil. - if ([self node].HasFlag(flutter::SemanticsFlags::kNamesRoute)) { - NSString* newName = [self accessibilityLabel]; - if (newName != nil && [newName length] > 0) { - return newName; - } - } - if ([self hasChildren]) { - for (SemanticsObject* child in self.children) { - NSString* newName = [child routeName]; - if (newName != nil && [newName length] > 0) { - return newName; - } - } - } - return nil; -} - - (NSString*)accessibilityLabel { if (![self isAccessibilityBridgeAlive]) return nil; @@ -300,6 +335,13 @@ flutter::SemanticsAction GetSemanticsActionForScrollDirection( return @([self node].label.data()); } +- (NSAttributedString*)accessibilityAttributedLabel { + NSString* label = [self accessibilityLabel]; + if (label.length == 0) + return nil; + return [self createAttributedStringFromString:label withAttributes:[self node].labelAttributes]; +} + - (NSString*)accessibilityHint { if (![self isAccessibilityBridgeAlive]) return nil; @@ -309,6 +351,13 @@ flutter::SemanticsAction GetSemanticsActionForScrollDirection( return @([self node].hint.data()); } +- (NSAttributedString*)accessibilityAttributedHint { + NSString* hint = [self accessibilityHint]; + if (hint.length == 0) + return nil; + return [self createAttributedStringFromString:hint withAttributes:[self node].hintAttributes]; +} + - (NSString*)accessibilityValue { if (![self isAccessibilityBridgeAlive]) return nil; @@ -331,6 +380,13 @@ flutter::SemanticsAction GetSemanticsActionForScrollDirection( return nil; } +- (NSAttributedString*)accessibilityAttributedValue { + NSString* value = [self accessibilityValue]; + if (value.length == 0) + return nil; + return [self createAttributedStringFromString:value withAttributes:[self node].valueAttributes]; +} + - (CGRect)accessibilityFrame { if (![self isAccessibilityBridgeAlive]) return CGRectMake(0, 0, 0, 0); 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 34bcb3f191..1dcf8371d6 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 @@ -160,6 +160,62 @@ class MockAccessibilityBridge : public AccessibilityBridgeIos { XCTAssertEqual([object accessibilityTraits], UIAccessibilityTraitButton); } +- (void)testSemanticsObjectBuildsAttributedString { + fml::WeakPtrFactory factory( + new flutter::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + flutter::SemanticsNode node; + node.label = "label"; + std::shared_ptr attribute = + std::make_shared(); + attribute->start = 1; + attribute->end = 2; + attribute->type = flutter::StringAttributeType::kSpellOut; + node.labelAttributes.push_back(attribute); + node.value = "value"; + attribute = std::make_shared(); + attribute->start = 2; + attribute->end = 3; + attribute->type = flutter::StringAttributeType::kSpellOut; + node.valueAttributes.push_back(attribute); + node.hint = "hint"; + std::shared_ptr local_attribute = + std::make_shared(); + local_attribute->start = 3; + local_attribute->end = 4; + local_attribute->type = flutter::StringAttributeType::kLocale; + local_attribute->locale = "en-MX"; + node.hintAttributes.push_back(local_attribute); + FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; + [object setSemanticsNode:&node]; + NSMutableAttributedString* expectedAttributedLabel = + [[NSMutableAttributedString alloc] initWithString:@"label"]; + NSDictionary* attributeDict = @{ + UIAccessibilitySpeechAttributeSpellOut : @YES, + }; + [expectedAttributedLabel setAttributes:attributeDict range:NSMakeRange(1, 1)]; + XCTAssertTrue( + [object.accessibilityAttributedLabel isEqualToAttributedString:expectedAttributedLabel]); + + NSMutableAttributedString* expectedAttributedValue = + [[NSMutableAttributedString alloc] initWithString:@"value"]; + attributeDict = @{ + UIAccessibilitySpeechAttributeSpellOut : @YES, + }; + [expectedAttributedValue setAttributes:attributeDict range:NSMakeRange(2, 1)]; + XCTAssertTrue( + [object.accessibilityAttributedValue isEqualToAttributedString:expectedAttributedValue]); + + NSMutableAttributedString* expectedAttributedHint = + [[NSMutableAttributedString alloc] initWithString:@"hint"]; + attributeDict = @{ + UIAccessibilitySpeechAttributeLanguage : @"en-MX", + }; + [expectedAttributedHint setAttributes:attributeDict range:NSMakeRange(3, 1)]; + XCTAssertTrue( + [object.accessibilityAttributedHint isEqualToAttributedString:expectedAttributedHint]); +} + - (void)testShouldTriggerAnnouncement { fml::WeakPtrFactory factory( new flutter::MockAccessibilityBridge());