From b7705127a6d5c3552974f4422671b6815a4db443 Mon Sep 17 00:00:00 2001 From: Chinmay Garde Date: Tue, 22 Oct 2019 17:50:01 -0700 Subject: [PATCH] Allow embedders to update preferrred locales. (flutter/engine#13238) This was previously only possible by sending an undocumented payload over an engine managed channel. --- .../shell/platform/embedder/embedder.cc | 82 +++++++++++++++++++ .../shell/platform/embedder/embedder.h | 44 +++++++++- .../platform/embedder/fixtures/main.dart | 9 ++ .../embedder/tests/embedder_unittests.cc | 58 +++++++++++++ 4 files changed, 192 insertions(+), 1 deletion(-) diff --git a/engine/src/flutter/shell/platform/embedder/embedder.cc b/engine/src/flutter/shell/platform/embedder/embedder.cc index 2b1a5d460c..3f2a972669 100644 --- a/engine/src/flutter/shell/platform/embedder/embedder.cc +++ b/engine/src/flutter/shell/platform/embedder/embedder.cc @@ -3,6 +3,7 @@ // found in the LICENSE file. #define FML_USED_ON_EMBEDDER +#define RAPIDJSON_HAS_STDSTRING 1 #include @@ -43,6 +44,8 @@ extern const intptr_t kPlatformStrongDillSize; #include "flutter/shell/platform/embedder/embedder_task_runner.h" #include "flutter/shell/platform/embedder/embedder_thread_host.h" #include "flutter/shell/platform/embedder/platform_view_embedder.h" +#include "rapidjson/rapidjson.h" +#include "rapidjson/writer.h" const int32_t kFlutterSemanticsNodeIdBatchEnd = -1; const int32_t kFlutterSemanticsCustomActionIdBatchEnd = -1; @@ -1491,3 +1494,82 @@ FlutterEngineResult FlutterEngineRunTask(FLUTTER_API_SYMBOL(FlutterEngine) : LOG_EMBEDDER_ERROR(kInvalidArguments, "Could not run the specified task."); } + +FlutterEngineResult FlutterEngineUpdateLocales(FLUTTER_API_SYMBOL(FlutterEngine) + engine, + const FlutterLocale** locales, + size_t locales_count) { + if (engine == nullptr) { + return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle."); + } + + if (locales_count == 0) { + return kSuccess; + } + + if (locales == nullptr) { + return LOG_EMBEDDER_ERROR(kInvalidArguments, "No locales were specified."); + } + + rapidjson::Document document; + auto& allocator = document.GetAllocator(); + + document.SetObject(); + document.AddMember("method", "setLocale", allocator); + + rapidjson::Value args(rapidjson::kArrayType); + args.Reserve(locales_count * 4, allocator); + for (size_t i = 0; i < locales_count; ++i) { + const FlutterLocale* locale = locales[i]; + const char* language_code_str = SAFE_ACCESS(locale, language_code, nullptr); + if (language_code_str == nullptr || ::strlen(language_code_str) == 0) { + return LOG_EMBEDDER_ERROR( + kInvalidArguments, + "Language code is required but not present in FlutterLocale."); + } + + const char* country_code_str = SAFE_ACCESS(locale, country_code, ""); + const char* script_code_str = SAFE_ACCESS(locale, script_code, ""); + const char* variant_code_str = SAFE_ACCESS(locale, variant_code, ""); + + rapidjson::Value language_code, country_code, script_code, variant_code; + + language_code.SetString(language_code_str, allocator); + country_code.SetString(country_code_str ? country_code_str : "", allocator); + script_code.SetString(script_code_str ? script_code_str : "", allocator); + variant_code.SetString(variant_code_str ? variant_code_str : "", allocator); + + // Required. + args.PushBack(language_code, allocator); + args.PushBack(country_code, allocator); + args.PushBack(script_code, allocator); + args.PushBack(variant_code, allocator); + } + document.AddMember("args", args, allocator); + + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + if (!document.Accept(writer)) { + return LOG_EMBEDDER_ERROR(kInternalInconsistency, + "Could not create locale payload."); + } + + const char* message = buffer.GetString(); + + if (message == nullptr || buffer.GetSize() == 0) { + return LOG_EMBEDDER_ERROR(kInternalInconsistency, + "Could not create locale update message."); + } + + auto platform_message = fml::MakeRefCounted( + "flutter/localization", // channel + std::vector{message, message + buffer.GetSize()}, // message + nullptr // response + ); + return reinterpret_cast(engine) + ->SendPlatformMessage(std::move(platform_message)) + ? kSuccess + : LOG_EMBEDDER_ERROR(kInternalInconsistency, + "Could not send message to update locale of " + "a running Flutter application."); +} diff --git a/engine/src/flutter/shell/platform/embedder/embedder.h b/engine/src/flutter/shell/platform/embedder/embedder.h index 5c19142b7e..0ffcbae6f7 100644 --- a/engine/src/flutter/shell/platform/embedder/embedder.h +++ b/engine/src/flutter/shell/platform/embedder/embedder.h @@ -778,6 +778,30 @@ typedef struct { FlutterLayersPresentCallback present_layers_callback; } FlutterCompositor; +typedef struct { + /// This size of this struct. Must be sizeof(FlutterLocale). + size_t struct_size; + /// The language code of the locale. For example, "en". This is a required + /// field. The string must be null terminated. It may be collected after the + /// call to `FlutterEngineUpdateLocales`. + const char* language_code; + /// The country code of the locale. For example, "US". This is a an optional + /// field. The string must be null terminated if present. It may be collected + /// after the call to `FlutterEngineUpdateLocales`. If not present, a + /// `nullptr` may be specified. + const char* country_code; + /// The script code of the locale. This is a an optional field. The string + /// must be null terminated if present. It may be collected after the call to + /// `FlutterEngineUpdateLocales`. If not present, a `nullptr` may be + /// specified. + const char* script_code; + /// The variant code of the locale. This is a an optional field. The string + /// must be null terminated if present. It may be collected after the call to + /// `FlutterEngineUpdateLocales`. If not present, a `nullptr` may be + /// specified. + const char* variant_code; +} FlutterLocale; + typedef struct { /// The size of this struct. Must be sizeof(FlutterProjectArgs). size_t struct_size; @@ -1404,7 +1428,7 @@ uint64_t FlutterEngineGetCurrentTime(); /// must only be made at the target time specified in that callback. /// Running the task before that time is undefined behavior. /// -/// @param[in] engine a running instance. +/// @param[in] engine A running engine instance. /// @param[in] task the task handle. /// /// @return The result of the call. @@ -1414,6 +1438,24 @@ FlutterEngineResult FlutterEngineRunTask(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterTask* task); +//------------------------------------------------------------------------------ +/// @brief Notify a running engine instance that the locale has been +/// updated. The preferred locale must be the first item in the list +/// of locales supplied. The other entries will be used as a +/// fallback. +/// +/// @param[in] engine A running engine instance. +/// @param[in] locales The updated locales in the order of preference. +/// @param[in] locales_count The count of locales supplied. +/// +/// @return Whether the locale updates were applied. +/// +FLUTTER_EXPORT +FlutterEngineResult FlutterEngineUpdateLocales(FLUTTER_API_SYMBOL(FlutterEngine) + engine, + const FlutterLocale** locales, + size_t locales_count); + #if defined(__cplusplus) } // extern "C" #endif diff --git a/engine/src/flutter/shell/platform/embedder/fixtures/main.dart b/engine/src/flutter/shell/platform/embedder/fixtures/main.dart index 67a546ad44..04c0e8c7dc 100644 --- a/engine/src/flutter/shell/platform/embedder/fixtures/main.dart +++ b/engine/src/flutter/shell/platform/embedder/fixtures/main.dart @@ -47,6 +47,7 @@ Float64List kTestTransform = () { }(); void signalNativeTest() native 'SignalNativeTest'; +void signalNativeCount(int count) native 'SignalNativeCount'; void signalNativeMessage(String message) native 'SignalNativeMessage'; void notifySemanticsEnabled(bool enabled) native 'NotifySemanticsEnabled'; void notifyAccessibilityFeatures(bool reduceMotion) native 'NotifyAccessibilityFeatures'; @@ -443,3 +444,11 @@ void can_display_platform_view_with_pixel_ratio() { }; window.scheduleFrame(); } + +@pragma('vm:entry-point') +void can_receive_locale_updates() { + window.onLocaleChanged = (){ + signalNativeCount(window.locales.length); + }; + signalNativeTest(); +} diff --git a/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests.cc b/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests.cc index a6a1d291a3..dc38064b27 100644 --- a/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests.cc +++ b/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests.cc @@ -2751,5 +2751,63 @@ TEST_F( latch.Wait(); } +TEST_F(EmbedderTest, CanUpdateLocales) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSoftwareRendererConfig(); + builder.SetDartEntrypoint("can_receive_locale_updates"); + fml::AutoResetWaitableEvent latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.Signal(); })); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Wait for the application to attach the listener. + latch.Wait(); + + FlutterLocale locale1 = {}; + locale1.struct_size = sizeof(locale1); + locale1.language_code = ""; // invalid + locale1.country_code = "US"; + locale1.script_code = ""; + locale1.variant_code = nullptr; + + FlutterLocale locale2 = {}; + locale2.struct_size = sizeof(locale2); + locale2.language_code = "zh"; + locale2.country_code = "CN"; + locale2.script_code = "Hans"; + locale2.variant_code = nullptr; + + std::vector locales; + locales.push_back(&locale1); + locales.push_back(&locale2); + + ASSERT_EQ( + FlutterEngineUpdateLocales(engine.get(), locales.data(), locales.size()), + kInvalidArguments); + + // Fix the invalid code. + locale1.language_code = "en"; + + ASSERT_EQ( + FlutterEngineUpdateLocales(engine.get(), locales.data(), locales.size()), + kSuccess); + + fml::AutoResetWaitableEvent check_latch; + context.AddNativeCallback( + "SignalNativeCount", + CREATE_NATIVE_ENTRY([&check_latch](Dart_NativeArguments args) { + ASSERT_EQ(tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)), + 2); + check_latch.Signal(); + })); + check_latch.Wait(); +} + } // namespace testing } // namespace flutter